How to replace a string in multiple files in linux

2019-01-07 01:49发布

I need to replace a string in a lot of files in a folder, with only ssh access to the server. How can I do this?

标签: linux string
22条回答
贼婆χ
2楼-- · 2019-01-07 02:07

If the file contains backslashes (paths usually) you can try something like this:

sed -i -- 's,<path1>,<path2>,g' *

ex:

sed -i -- 's,/foo/bar,/new/foo/bar,g' *.sh (in all shell scripts available)
查看更多
Explosion°爆炸
3楼-- · 2019-01-07 02:10

There are a few standard answers to this already listed. Generally, you can use find to recursively list the files and then do the operations with sed or perl.

For most quick uses, you may find the command rpl is much easier to remember. Here is replacement (foo -> bar), recursively on all files:

rpl -R foo bar .

You'll probably need to install it (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents.
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

To use it, pip install repren. Check the README for examples.

查看更多
放我归山
4楼-- · 2019-01-07 02:10

To replace a string in multiple files you can use:

grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'

E.g.

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

Source blog

查看更多
仙女界的扛把子
5楼-- · 2019-01-07 02:12

To replace a path within files (avoiding escape characters) you may use the following command:

sed -i 's@old_path@new_path@g'

The @ sign means that all of the special characters should be ignored in a following string.

查看更多
Fickle 薄情
6楼-- · 2019-01-07 02:13

Below command can be used to first search the files and replace the files

find . |xargs grep search string | sed 's/search string/new string/g'

e.g find . |xargs grep abc | sed 's/abc/xyz/g'

查看更多
迷人小祖宗
7楼-- · 2019-01-07 02:15

The first line occurrences of "foo" will be replaced with "bar". And you can using the second line to check.

grep -rl 'foo' . | xargs sed -i 's/foo/bar/g'
grep 'foo' -r * | awk -F: {'print $1'} | sort -n | uniq -c
查看更多
登录 后发表回答