替换整行的sed正则表达式为:

huangapple go评论48阅读模式
英文:

sed replace with regex whole line

问题

有两个文件:

file1

dir='/root/path/to/somewhere/'
sed -zre "s|dir=(.*)'$|dir='$(echo $dir)'|g" -i file2

file2

dir='/blah/blah/'

我想要执行以下操作:

查找一行包含 dir=(.*) 并替换为 $dir 的值。

我运行了 bash file1,但它没有在 file2 中替换任何内容。

英文:

There are two files:

file1:

dir='/root/path/to/somewhere/'
sed -zre "s|dir=(.*)'$|dir='$(echo $dir)'|g" -i file2

file2:

dir='/blah/blah/'

I want to do this:

> find a line having dir=(.*) and replace with the value of $dir

I run bash file1, but it doesn't replace anything in `file21.

答案1

得分: 2

以下的 sed 命令应该适用于你:

sed -i "s|dir=.*|dir='$dir'|" file2

请注意,在这个命令中移除了不正确的选项 -zre,还移除了你的 sed 命令中多余的命令替代。特别要注意的是 -z 的使用,它将完整的输入文件读入单行文本,因此无法匹配 '$,因为单引号的闭合不是文件中的最后一个字符。

如果你想避免重复两次写 dir=,可以使用一个捕获组:

sed -E -i.bak "s|(dir=).*|'$dir'|" file2
英文:

Following sed should work for you:

sed -i "s|dir=.*|dir='$dir'|" file2

Note removal of incorrect options -zre in this command and removal of redundant command substitution from your sed command.

Specifically problematic is use of -z that slurps complete input file in a single line of text thus failing to match '$ since closing single quote is not the last character in file.

If you want to avoid repeating dir= 2 times then use a capture group:

sed -E -i.bak "s|(dir=).*|'$dir'|" file2

huangapple
  • 本文由 发表于 2023年6月5日 01:00:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定