Sed:将字符串变量替换为字符串变量[duplicate]

时间:2022-01-17 16:49:04

This question already has an answer here:

这个问题已经有了答案:

I have a file called ethernet containing multiple lines. I have saved one of these lines as a variable called old_line. The contents of this variable looks like this:

我有一个名为ethernet的文件,包含多行。我已经将其中一个行保存为一个名为old_line的变量。该变量的内容如下:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="2r:11:89:89:9g:ah", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

I have created a second variable called new_line that is similar to old_line but with some modifications in the text.

我创建了第二个变量new_line,它与old_line类似,但在文本中做了一些修改。

I want to substitute the contents of old_line with the contents of new_line using sed. So far I have the following, but it doesn't work:

我想用sed将old_line的内容替换为new_line的内容。到目前为止,我有以下几点,但不管用:

sed -i "s/${old_line}/${new_line}/g" ethernet

2 个解决方案

#1


1  

You need to escape your oldline so that it contains no regex special characters, luckily this can be done with sed.

您需要从旧行中脱离,以便它不包含regex特殊字符,幸运的是,这可以通过sed完成。

old_line=$(echo "${old_line}" | sed -e 's/[]$.*[\^]/\\&/g' )
sed -i -e "s/${old_line}/${new_line}/g" ethernet

#2


5  

Since ${old_line} contains many regex special metacharacters like *, ? etc therefore your sed is failing.

因为${old_line}包含许多regex特殊的元字符,如*,?所以你的战略失败了。

Use this awk command instead that uses no regex:

使用此awk命令,而不使用regex:

awk -v old="$old_line" -v new="$new_line" 'p=index($0, old) {
      print substr($0, 1, p-1) new substr($0, p+length(old)) }' ethernet

#1


1  

You need to escape your oldline so that it contains no regex special characters, luckily this can be done with sed.

您需要从旧行中脱离,以便它不包含regex特殊字符,幸运的是,这可以通过sed完成。

old_line=$(echo "${old_line}" | sed -e 's/[]$.*[\^]/\\&/g' )
sed -i -e "s/${old_line}/${new_line}/g" ethernet

#2


5  

Since ${old_line} contains many regex special metacharacters like *, ? etc therefore your sed is failing.

因为${old_line}包含许多regex特殊的元字符,如*,?所以你的战略失败了。

Use this awk command instead that uses no regex:

使用此awk命令,而不使用regex:

awk -v old="$old_line" -v new="$new_line" 'p=index($0, old) {
      print substr($0, 1, p-1) new substr($0, p+length(old)) }' ethernet