我在许多不同的目录中有数百个[大多数不同]文件,它们都有相同的5行文本,我需要经常编辑。例如:
/home/blah.txt
/home/hello/superman.txt
/home/hello/dreams.txt
/home/55/instruct.txt
and so on...
5行文本按顺序排列,但从所有.txt文件中的不同位置开始。例如:
line 400 this is line 1
line 401 this is line 2
line 402 this is line 3
line 403 this is line 4
line 404 this is line 5
/home/hello/superman.txt:
line 23 this is line 1
line 24 this is line 2
line 25 this is line 3
line 26 this is line 4
line 27 this is line 5
如何在所有.txt文件中找到并替换这5行文本?
答案 0 :(得分:3)
步骤1:打开包含所有相关文件的vim。例如,使用zshell,您可以执行以下操作:
vim **/*.txt
假设您想要的文件是当前树下任何位置的.txt文件。或者创建一个单行脚本来打开你需要的所有文件(看起来像这样:“vim dir1 / file1 dir2 / file2 ......”)
第2步:在vim中,执行:
:bufdo %s/this is line 1/this is the replacement for line 1/g | w
:bufdo %s/this is line 2/this is the replacement for line 2/g | w
...
bufdo命令在所有打开的缓冲区中重复执行命令。在这里,执行查找和替换,然后执行写入。 :帮助bufdo更多。
答案 1 :(得分:0)
如果您想编写脚本,特别是如果您的号码更改但必须保留在新行中:
for i in */*txt
do
DIR=`dirname $i` # keep directory name somewhere
FILE=`basename $i .txt` # remove .txt
cat $i | sed 's/line \(.*\) this is line \(.*\)/NEW LINE with number \1 this is NEW LINE \2/' > $DIR/$FILE.new # replace line XX this is line YYY => NEW LINE XX this is NEW LINE YY, keeping the values XX and YY
#mv -f $DIR/$FILE.new $i # uncomment this when you're sure you want to replace orig file
done
此致