如何在使用sed替换文本时保留新的行和格式?

时间:2022-05-14 20:10:26

I have a template file like this

我有一个这样的模板文件

$ cat template.txt
QWERTY
~SQL~
ASDFG

I need to substitute the "~SQL~" string in the template file with following text. This text is stored in a variable

我需要用下面的文本替换模板文件中的“~SQL~”字符串。该文本存储在一个变量中

SELECT COL1,
       COL2,
       COL3
FROM TABLE;

I tried the following code, but got an error: sed: -e expression #1, char 20: unterminated `s' command

我尝试了下面的代码,但是得到了一个错误:sed: -e表达式#1,char 20:未终止的' s'命令。

$ query='SELECT COL1,
>        COL2,
>        COL3
> FROM TABLE;'
$ 
$ sed "s/~SQL~/$query/" template.txt
sed: -e expression #1, char 20: unterminated `s' command

If I remove the new lines from "query", the sed command works fine

如果我从“query”中删除新行,则sed命令可以正常工作

$ query='SELECT COL1, COL2, COL3 FROM TABLE;'
$ sed "s/~SQL~/$query/" template.txt
QWERTY
SELECT COL1, COL2, COL3 FROM TABLE;
ASDFG

I would like to preserve the new lines and formatting while substituting the text. How do I achieve this?

我希望在替换文本时保留新的行和格式。我如何做到这一点?

2 个解决方案

#1


2  

You can use this awk:

你可以使用这个awk:

awk -v q="$query" '/~SQL~/{$0 = q} 1' file
QWERTY
SELECT COL1,
       COL2,
       COL3,
FROM TABLE;
ASDFG

#2


0  

You can do this:

你可以这样做:

query='SELECT COL1,\n       COL2,\n       COL3\nFROM TABLE;'
sed "s/~SQL~/$query/" template.txt

#1


2  

You can use this awk:

你可以使用这个awk:

awk -v q="$query" '/~SQL~/{$0 = q} 1' file
QWERTY
SELECT COL1,
       COL2,
       COL3,
FROM TABLE;
ASDFG

#2


0  

You can do this:

你可以这样做:

query='SELECT COL1,\n       COL2,\n       COL3\nFROM TABLE;'
sed "s/~SQL~/$query/" template.txt