使用 Sed 用字符串变量替换字符串变量 [英] Replace string variable with string variable using Sed
问题描述
我有一个名为 ethernet 的文件,其中包含多行.我已将其中一行保存为名为 old_line 的变量.该变量的内容如下所示:
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:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="2r:11:89:89:9g:ah", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
我创建了一个名为 new_line 的第二个变量,它类似于 old_line,但对文本做了一些修改.
I have created a second variable called new_line that is similar to old_line but with some modifications in the text.
我想使用 sed 将 old_line 的内容替换为 new_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 -i "s/${old_line}/${new_line}/g" ethernet
推荐答案
您需要对 oldline
进行转义,使其不包含正则表达式特殊字符,幸运的是这可以通过 sed 完成.
You need to escape your oldline
so that it contains no regex special characters, luckily this can be done with sed.
old_line=$(echo "${old_line}" | sed -e 's/[]$.*[^]/\&/g' )
sed -i -e "s/${old_line}/${new_line}/g" ethernet
这篇关于使用 Sed 用字符串变量替换字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!