如何使用sed将变量字符串替换为另一个变量字符串

时间:2020-06-15 21:38:05

标签: bash shell sed

因此,我尝试用多行替换文件中的行内容,但无法正常工作。详细信息如下:

文本文件:/home/user1/file1.txt

文件内容:

The quick brown fox
The quick brown fox jumps over the lazy fat dog
Little brown and the lazy fat dog
Lazy dog and the fat lion

string1 = "The quick brown fox jumps over the lazy fat dog"

string2 = "The quick little black fox jumps over the lazy fat dog The quick big brown fox jumps over the lazy fat dog The lazy little brown fox jumps over the lazy fat dog"

Shell脚本文件:/home/user1/replace_me.sh

因此,如果我使用以下sid command运行shell脚本文件,则文件内容将更改为:

The quick brown fox
The quick little black fox jumps over the lazy fat dog
The quick big brown fox jumps over the lazy fat dog
The lazy little brown fox jumps over the lazy fat dog 
Little brown and the lazy fat dog 
Lazy dog and the fat lion

我使用How to replace a variable with another variable using sedReplace a word with multiple lines using sed?作为参考:

这些是我没有运气尝试过的命令:(

sed -i "s/$string1/$string2/" /home/user1/file1.txt

sed -i "/${string1}/{s/^.*/${string2}/" /home/user1/file1.txt

以下是shell脚本文件的内容:

#!/bin/bash

string1="The quick brown fox jumps over the lazy fat dog"

string2="The quick little black fox jumps over the lazy fat dog
The quick big brown fox jumps over the lazy fat dog
The lazy little brown fox jumps over the lazy fat dog"

sed -i "s/$string1/$string2/" /home/user1/file1.txt

#sed -i "/${string1}/{s/^.*/${string2}/" /home/user1/file1.txt

2 个答案:

答案 0 :(得分:1)

在多行文件中替换行内容

sed中,命令用换行符分隔。因此,当sed看到s/blabla/blabla<newline>被解析为完整命令并退出而缺少结束符/时退出。

您可以用替换字符串中的每个换行符替换两个字符\n,然后可以用sed替换换行符。

string2=${string2//$'\n'/\\n}
sed "s/$string1/$string2/"

请注意,seds命令的第一部分解析为正则表达式,并在替换字符串中解析一些字符串(\1 & \L \U等等)。

这仅在string1中没有换行符的情况下有效。使用GNU sed,您可以使用string1选项在-z中使用换行符,它将导致将输入解析为零终止的字符串。

答案 1 :(得分:0)

这可能对您有用(GNU sed):

echo "$string2" | sed "s/$string1/cat -/e" file

这将使用替换命令中的e标志使用回显管道中的stdin将$string2发送到stdout。

应注意,$string1必须是一行,并且不包含任何元字符。如果$string1确实包含特殊字符,则可以在bash中使用:

echo "$string2" |
sed 's/'"$(<<<"$string3" sed 's/[][^$.*&\/]/\\&/g')"'/cat -/e' file

这会转义$string1中的任何元字符,然后这些元字符将成为替换正则表达式的LHS。