Linux 如何通过vim从多个文件中添加/删除相同的文本行?

Linux 如何通过vim从多个文件中添加/删除相同的文本行?,linux,vim,debian,Linux,Vim,Debian,我在许多不同的目录中有数百个[大部分是不同的]文件,其中都有相同的5行文本,我需要经常编辑。例如: /home/blah.txt /home/hello/superman.txt /home/hello/dreams.txt /home/55/instruct.txt and so on... 这5行文本按顺序排列,但在所有.txt文件中从不同的位置开始。例如: /home/blah.txt /home/hello/superman.txt /home/hello/dreams.txt /ho

我在许多不同的目录中有数百个[大部分是不同的]文件,其中都有相同的5行文本,我需要经常编辑。例如:

/home/blah.txt
/home/hello/superman.txt
/home/hello/dreams.txt
/home/55/instruct.txt
and so on...
这5行文本按顺序排列,但在所有.txt文件中从不同的位置开始。例如:

/home/blah.txt
/home/hello/superman.txt
/home/hello/dreams.txt
/home/55/instruct.txt
and so on...
在/home/blah.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行文本?

步骤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:打开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了解更多信息。

如果您想编写脚本,尤其是如果您的数字发生了变化,但必须保留在新行中:

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

关于,

如果您想编写脚本,特别是如果您的数字发生了变化,但必须保留在新行中:

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
问候,