Best way to do a find/replace in several files?

后端 未结 5 541
北恋
北恋 2021-01-30 01:56

what\'s the best way to do this? I\'m no command line warrior, but I was thinking there\'s possibly a way of using grep and cat.

I just want to

5条回答
  •  有刺的猬
    2021-01-30 02:11

    As Paul said, you want to first find the files you want to edit and then edit them. An alternative to using find is to use GNU grep (the default on Ubuntu), e.g.:

    grep -r -l from . | xargs -0 -n 1 sed -i -e 's/from/to/g'
    

    You can also use ack-grep (sudo apt-get install ack-grep or visit http://petdance.com/ack/) as well, if you know you only want a certain type of file, and want to ignore things in version control directories. e.g., if you only want text files,

    ack -l --print0 --text from | xargs -0 -n 1 sed -i -e 's/from/to/g'
    # `from` here is an arbitrary commonly occurring keyword
    

    An alternative to using sed is to use perl which can process multiple files per command, e.g.,

    grep -r -l from . | xargs perl -pi.bak -e 's/from/to/g'
    

    Here, perl is told to edit in place, making a .bak file first.

    You can combine any of the left-hand sides of the pipe with the right-hand sides, depending on your preference.

提交回复
热议问题