Pat*_*art 3 regex bash sed find
我知道以下命令可用于以递归方式替换特定字符串的所有实例:
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
Run Code Online (Sandbox Code Playgroud)
我希望将此作为输出:
This line containing oldstring should remain untouched
matchstr sometext newstring somethingelse
Run Code Online (Sandbox Code Playgroud)
任何关于我如何进行的建议将不胜感激.
你可以这样做:
sed -i '/^matchstr/{s/oldstring/newstring/g}'
Run Code Online (Sandbox Code Playgroud)
即
find /path/to/files -type f -print0 | \
xargs -0 sed -i '/^matchstr/{s/oldstring/newstring/g}'
Run Code Online (Sandbox Code Playgroud)
第一个/^matchstr/查找匹配该正则表达式的行,并执行这些行s/old/new/g.