Find and replace a particular term in multiple files

纵然是瞬间 提交于 2019-12-17 22:16:42

问题


How can I replace a particular term in multiple files in Linux?

For instance, I have a number of files in my directory:

file1.txt file2.txt file3.txt

And I need to find a word "searchword" and replace it with "replaceword".


回答1:


sed -i.bak 's/searchword/replaceword/g' file*.txt
# Or sed -i.bak '/searchword/s/searchword/replaceword/g' file*.txt

With bash 4.0, you can do recursive search for files

#!/bin/bash
shopt -s globstar
for file in **/file*.txt
do 
  sed -i.bak 's/searchword/replaceword/g' $file
  # or sed -i.bak '/searchword/s/searchword/replaceword/g' $file
done

Or with GNU find

find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;



回答2:


Nothing spectacular but thought this might be of help to others. Though you can write a shell script to do this easily, this one-liner is perhaps easier:

grep -lr -e '<searchthis>' * | xargs sed -i 's/<searchthis>/<replacewith>/g'



回答3:


Use an ed script

Although sed now has an in-place edit option, you can also use the ed or ex program for this purpose...

for i in "$@"; do ed "$i" << \eof; done
1,$s/searchword/replaceword/g
w
q
eof



回答4:


This ruby script worked for me, also renames the files/folders with that typo in too.




回答5:


Try mffr if you are in a git repo

pip install mffr
mffr searchword replaceword


来源:https://stackoverflow.com/questions/2263925/find-and-replace-a-particular-term-in-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!