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:15

"You could also use find and sed, but I find that this little line of perl works nicely.

perl -pi -w -e 's/search/replace/g;' *.php
  • -e means execute the following line of code.
  • -i means edit in-place
  • -w write warnings
  • -p loop

" (Extracted from http://www.liamdelahunty.com/tips/linux_search_and_replace_multiple_files.php)

My best results come from using perl and grep (to ensure that file have the search expression )

perl -pi -w -e 's/search/replace/g;' $( grep -rl 'search' )
查看更多
你好瞎i
3楼-- · 2019-01-07 02:16

Similar to Kaspar's answer but with the g flag to replace all the occurrences on a line.

find ./ -type f -exec sed -i 's/string1/string2/g' {} \;

For global case insensitive:

find ./ -type f -exec sed -i 's/string1/string2/gI' {} \;
查看更多
叛逆
4楼-- · 2019-01-07 02:17

If you have list of files you can use

replace "old_string" "new_string" -- file_name1 file_name2 file_name3

If you have all files you can use

replace "old_string" "new_string" -- *

If you have list of files with extension, you can use

replace "old_string" "new_string" -- *.extension
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-07 02:19

In case your string has a forward slash(/) in it, you could change the delimiter to '+'.

find . -type f -exec sed -i 's+http://example.com+https://example.com+g' {} +

This command would run recursively in the current directory.

查看更多
登录 后发表回答