使用 sed 和 grep 批量修改文件指定内容

/opt/path 目录下查找hello,并将所有的hello替换为world

sed -i 's/hello/world/g' `grep -rl hello /opt/path`

/opt/path 目录下查找hello/hello,并将所有的hello/hello替换为world/world

sed -i 's/hello\/hello/world\/world/g' `grep -rl 'hello/hello' /opt/path`

The s command (as in substitute) is probably the most important in sed and has a lot of different options. The syntax of the s command is ‘s/regexp/replacement/flags’.

Its basic concept is simple: the s command attempts to match the pattern space against the supplied regular expression regexp; if the match is successful, then that portion of the pattern space which was matched is replaced with replacement.

For details about regexp syntax see Regular Expression Addresses.

The replacement can contain \n (n being a number from 1 to 9, inclusive) references, which refer to the portion of the match which is contained between the nth \( and its matching \). Also, the replacement can contain unescaped & characters which reference the whole matched portion of the pattern space.

The / characters may be uniformly replaced by any other single character within any given s command. The / character (or whatever other character is used in its stead) can appear in the regexp or replacement only if it is preceded by a \ character.


关于本文

参考资料

  1. http://www.gnu.org/software/sed/manual/sed.html

你可能感兴趣的:(使用 sed 和 grep 批量修改文件指定内容)