美文网首页
使用 sed 和 grep 批量修改文件指定内容

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

作者: 侠骨留香 | 来源:发表于2019-11-20 10:43 被阅读0次

    /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 ‘<samp>s/<var style="font-style: italic; font-weight: inherit;">regexp</var>/<var style="font-style: italic; font-weight: inherit;">replacement</var>/<var style="font-style: italic; font-weight: inherit;">flags</var></samp>’.

    Its basic concept is simple: the s command attempts to match the pattern space against the supplied regular expression <var style="font-style: italic; font-weight: inherit;">regexp</var>; if the match is successful, then that portion of the pattern space which was matched is replaced with <var style="font-style: italic; font-weight: inherit;">replacement</var>.

    For details about <var style="font-style: italic; font-weight: inherit;">regexp</var> syntax see Regular Expression Addresses.

    The <var style="font-style: italic; font-weight: inherit;">replacement</var> can contain \<var style="font-style: italic; font-weight: inherit;">n</var> (<var style="font-style: italic; font-weight: inherit;">n</var> being a number from 1 to 9, inclusive) references, which refer to the portion of the match which is contained between the <var style="font-style: italic; font-weight: inherit;">n</var>th \( and its matching \). Also, the <var style="font-style: italic; font-weight: inherit;">replacement</var> 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 <var style="font-style: italic; font-weight: inherit;">regexp</var> or <var style="font-style: italic; font-weight: inherit;">replacement</var> only if it is preceded by a \ character.


    关于本文

    参考资料

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

    相关文章

      网友评论

          本文标题:使用 sed 和 grep 批量修改文件指定内容

          本文链接:https://www.haomeiwen.com/subject/cuanictx.html