How can I replace a particular term in multiple files in Linux?
如何在Linux中替换多个文件中的特定术语?
For instance, I have a number of files in my directory:
例如,我的目录中有许多文件:
file1.txt file2.txt file3.txt
file1.txt file2.txt file3.txt
And I need to find a word "searchword" and replace it with "replaceword".
我需要找到一个单词“searchword”并将其替换为“replaceword”。
5 个解决方案
#1
14
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
使用bash 4.0,您可以对文件进行递归搜索
#!/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
或者用GNU查找
find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;
#2
10
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:
没什么了不起的,但认为这对其他人有帮助。虽然您可以编写一个shell脚本来轻松完成此操作,但这个单行程可能更容易:
grep -lr -e '<searchthis>' * | xargs sed -i 's/<searchthis>/<replacewith>/g'
#3
2
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...
虽然sed现在有一个就地编辑选项,你也可以使用ed或ex程序来达到这个目的......
for i in "$@"; do ed "$i" << \eof; done
1,$s/searchword/replaceword/g
w
q
eof
#4
0
This ruby script worked for me, also renames the files/folders with that typo in too.
这个ruby脚本对我有用,也用这个拼写错误重命名文件/文件夹。
#5
0
Try mffr if you are in a git repo
如果你在git repo中尝试mffr
pip install mffr
mffr searchword replaceword
#1
14
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
使用bash 4.0,您可以对文件进行递归搜索
#!/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
或者用GNU查找
find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;
#2
10
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:
没什么了不起的,但认为这对其他人有帮助。虽然您可以编写一个shell脚本来轻松完成此操作,但这个单行程可能更容易:
grep -lr -e '<searchthis>' * | xargs sed -i 's/<searchthis>/<replacewith>/g'
#3
2
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...
虽然sed现在有一个就地编辑选项,你也可以使用ed或ex程序来达到这个目的......
for i in "$@"; do ed "$i" << \eof; done
1,$s/searchword/replaceword/g
w
q
eof
#4
0
This ruby script worked for me, also renames the files/folders with that typo in too.
这个ruby脚本对我有用,也用这个拼写错误重命名文件/文件夹。
#5
0
Try mffr if you are in a git repo
如果你在git repo中尝试mffr
pip install mffr
mffr searchword replaceword