我知道可以使用以下命令以递归方式替换特定字符串的所有实例:
find / path / to / files -type f -print0 | xargs -0 sed -i's / oldstring / newstring / g'
但是,我只需要以以特定字符串开头的行(“matchstr”)执行此操作。
例如,如果文件包含以下行:
This line containing oldstring should remain untouched
matchstr sometext oldstring somethingelse
我希望将此作为输出:
This line containing oldstring should remain untouched
matchstr sometext newstring somethingelse
任何有关我如何进行的建议都将不胜感激。
答案 0 :(得分:6)
你可以这样做:
sed -i '/^matchstr/{s/oldstring/newstring/g}'
即
find /path/to/files -type f -print0 | \
xargs -0 sed -i '/^matchstr/{s/oldstring/newstring/g}'
第一个/^matchstr/
查找与该正则表达式匹配的行,对于这些行,执行s/old/new/g
。
答案 1 :(得分:4)
您可以使用sed轻松完成此操作:
sed -e '/^matchstr/ s/oldstring/newstring/g' inputfile
/^matchstr/
充当条件;只有当正则表达式匹配时才会执行以下块。在这种情况下,我们在行的开头寻找matchstr
。