2012-06-23 21 views
0

我有很多不同的目錄中的[大多數不同的]文件,它們都有相同的5行文本,我需要頻繁編輯。例如:如何通過vim在多個文件中添加/刪除相同的文本行?

/home/blah.txt 
/home/hello/superman.txt 
/home/hello/dreams.txt 
/home/55/instruct.txt 
and so on... 

5行文字依次排列,但是在所有.txt文件的不同位置開始。例如:

在/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 

我如何查找和替換在所有這些5行文字的.txt文件?

回答

3

第1步:打開所有相關文件的vim。例如,使用zshell,你可以這樣做:

vim **/*.txt 

假設你想要的文件是當前樹下任何地方的.txt文件。或創建一個行腳本打開所有你需要的文件(這將是這樣的:「VIM DIR1/DIR2文件1 /文件2 ...」)

步驟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獲得更多。

+0

真棒感謝你們 – supyall

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 

問候,

相關問題