How to do a recursive find/replace of a string wit

2018-12-31 14:41发布

How do I find and replace every occurrence of:

subdomainA.example.com

with

subdomainB.example.com

in every text file under the /home/www/ directory tree recursively?

30条回答
君临天下
2楼-- · 2018-12-31 15:16

For replace all occurrences in a git repository you can use:

git ls-files -z | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'

See List files in local git repo? for other options to list all files in a repository. The -z options tells git to separate the file names with a zero byte, which assures that xargs (with the option -0) can separate filenames, even if they contain spaces or whatnot.

查看更多
墨雨无痕
3楼-- · 2018-12-31 15:17

For anyone using silver searcher (ag)

ag SearchString -l0 | xargs -0 sed -i 's/SearchString/Replacement/g'

Since ag ignores git/hg/svn file/folders by default, this is safe to run inside a repository.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 15:17

just to avoid to change also

  • NearlysubdomainA.example.com
  • subdomainA.example.comp.other

but still

  • subdomainA.example.com.IsIt.good

(maybe not good in the idea behind domain root)

find /home/www/ -type f -exec sed -i 's/\bsubdomainA\.example\.com\b/\1subdomainB.example.com\2/g' {} \;
查看更多
几人难应
5楼-- · 2018-12-31 15:17

According to this blog post:

find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'
查看更多
谁念西风独自凉
6楼-- · 2018-12-31 15:18

To cut down on files to recursively sed through, you could grep for your string instance:

grep -rl <oldstring> /path/to/folder | xargs sed -i s^<oldstring>^<newstring>^g

If you run man grep you'll notice you can also define an --exlude-dir="*.git" flag if you want to omit searching through .git directories, avoiding git index issues as others have politely pointed out.

Leading you to:

grep -rl --exclude-dir="*.git" <oldstring> /path/to/folder | xargs sed -i s^<oldstring>^<newstring>^g
查看更多
荒废的爱情
7楼-- · 2018-12-31 15:18

You can use awk to solve this as below,

for file in `find /home/www -type f`
do
   awk '{gsub(/subdomainA.example.com/,"subdomainB.example.com"); print $0;}' $file > ./tempFile && mv ./tempFile $file;
done

hope this will help you !!!

查看更多
登录 后发表回答