Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Find/sed:如何递归搜索/替换文件中的字符串,但仅搜索与特定regexp匹配的行_Regex_Bash_Sed_Find - Fatal编程技术网

Find/sed:如何递归搜索/替换文件中的字符串,但仅搜索与特定regexp匹配的行

Find/sed:如何递归搜索/替换文件中的字符串,但仅搜索与特定regexp匹配的行,regex,bash,sed,find,Regex,Bash,Sed,Find,我知道可以使用以下命令以递归方式将特定字符串的所有实例替换为另一个: find/path/to/files-type f-print0 | xargs-0sed-i's/oldstring/newstring/g' 但是,我只需要对以特定字符串(“matchstr”)开头的行执行此操作 例如,如果文件包含以下行: This line containing oldstring should remain untouched matchstr sometext oldstring something

我知道可以使用以下命令以递归方式将特定字符串的所有实例替换为另一个:

find/path/to/files-type f-print0 | xargs-0sed-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

如有任何关于如何继续的建议,我们将不胜感激。

您可以使用sed轻松完成此操作:

sed -e '/^matchstr/ s/oldstring/newstring/g' inputfile
/^matchstr/
作为一个条件;它使它仅在正则表达式匹配时执行以下块。在本例中,我们将在行首查找
matchstr

您可以执行以下操作:

sed -i '/^matchstr/{s/oldstring/newstring/g}'


第一个
/^matchstr/
查找与该正则表达式匹配的行,并对这些行执行
s/old/new/g

实际上不需要括号或空格-您可以使用
sed-i'/^matchstr/s/oldstring/newstring/g'
find /path/to/files -type f -print0 | \
  xargs -0 sed -i '/^matchstr/{s/oldstring/newstring/g}'