find and replace in multiple files on command line

2019-01-30 00:30发布

How do i find and replace a string on command line in multiple files on unix?

5条回答
太酷不给撩
2楼-- · 2019-01-30 01:04

I always did that with ed scripts or ex scripts.

for i in "$@"; do ex - "$i" << 'eof'; done
%s/old/new/
x
eof

The ex command is just the : line mode from vi.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-30 01:06

Like the Zombie solution (and faster I assume) but with sed (standard on many distros and OSX) instead of Perl :

find . -name '*.py' | xargs sed -i .bak 's/foo/bar/g'

This will replace all foo occurences in your Python files below the current directory with bar and create a backup for each file with the .py.bak extension.

And to remove de .bak files:

find . -name "*.bak" -delete
查看更多
做自己的国王
4楼-- · 2019-01-30 01:17

with recent bash shell, and assuming you do not need to traverse directories

for file in *.txt
do
while read -r line
do
    echo ${line//find/replace} > temp        
done <"file"
mv temp "$file"
done 
查看更多
该账号已被封号
5楼-- · 2019-01-30 01:20

Using find and sed with name or directories with space use this:

find . -name '*.py' -print0 | xargs -0 sed -i 's/foo/bar/g'
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-30 01:22

there are many ways .But one of the answers would be:

find . -name '*.html' |xargs perl -pi -e 's/find/replace/g'
查看更多
登录 后发表回答