This question already has an answer here:
这个问题已经有了答案:
- “sed” special characters handling 3 answers
- “sed”特殊字符处理3个答案。
- Is it possible to escape regex metacharacters reliably with sed 2 answers
- 有可能用sed 2的答案可靠地逃脱regex元字符吗
- Escape a string for a sed replace pattern 14 answers
- 为sed replace模式14答案转义字符串
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