查找并替换文件中的字符串 [英] find and replace string in a file
本文介绍了查找并替换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找并替换文件文件夹中的字符串.
I'm trying to find and replace a string in a folder of files.
有人可以帮我吗?
我的脚本如下:
#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
if [ -f $f -a -r $f ]; then
/bin/cp -f $f $BPATH
sed "s/$OLD/$NEW/g" "$f"
else
echo "Error: Cannot read $f"
fi
done
现在,这似乎找到了字符串"This is a",并替换为"I am a",但这仅显示在屏幕上.
Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.
我需要它来替换文件本身.
I need it to replace in the files themselves.
谢谢
推荐答案
使用sed
的-i
选项进行适当的更改:
Use the -i
option of sed
to make the changes in place:
sed -i "s/$OLD/$NEW/g" "$f"
^^
这篇关于查找并替换文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文