Friday, March 4, 2011

Re: search and replace with word list

On 2011-03-02 14:29, Raleigh Rinehart wrote:
> Suppose I have in one file several lines (could be 100s of such lines)
> like this:
> ..
> <Folder><![CDATA[C:\work\sources\foo\bar\baz\MODULEX\lib]]></Folder>
> ..
>
> Now in another file I have a list of words, in this instance separated
> by newlines, but could be changed to space/tab/comma/etc delimited.
> The number of words equals the number of lines that match from the
> first file.
>
> Now what I would like to do is to replace each occurrence of MODULEX
> in file1 with the corresponding word in file 2.
>
> By corresponding I mean if the lines (from file 1) and the words (from
> file 2) were both well ordered sets then the match is determined by
> the index into the set, or in other words a one-to-one correspondence.

I think what I would do is paste the two files together side-by-side.
You can do this in vim using visual-block mode, or if you're on a unix
machine you could use the paste command.

:%!paste file2.txt file1.txt
or
$ paste file2.txt file1.txt | vim -

After that it's just a simple line-by-line substitution. You could even
use sed if you wanted.

:%s/\v(\w+)\t(.*)MODULEX/\2\1/

No comments:

Post a Comment