supyall
supyall

Reputation: 3

how to add/remove identical lines of text from multiple files via vim?

i have hundreds of [mostly different] files in many different directories that all have an identical 5 lines of text in them that i need to frequently edit. example:

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

the 5 lines of text are in sequence but begin at different locations in all of the .txt files. example:

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

how can i find and replace those 5 lines of text in all of the .txt files?

Upvotes: 0

Views: 1060

Answers (2)

michauko
michauko

Reputation: 101

If you want to script it, especially if your numbers change but must be kept in the new lines:

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

Regards,

Upvotes: 0

PonyEars
PonyEars

Reputation: 2254

Step 1: Open vim with all the files in question. Using zshell, for instance, you could do:

vim **/*.txt

assuming the files you want are .txt files anywhere under the current tree. Or create a one-line script to open all the files you need (which would look like: "vim dir1/file1 dir2/file2 ...")

Step 2: In vim, do:

: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 
...

The bufdo command repeats your commands across all the open buffers. Here, perform a find and replace followed by a write. :help bufdo for more.

Upvotes: 5

Related Questions