0

I have rather large files in which I need to substitute NX for N1 but only if the line already contains NX as a pattern. So far I do it manually by first searching for occurrences of NX with:

/NX

and then using

'<,'>s/N1/NX

But the files are really large and long and the chances of me making a mistake during this manual procedure are very high. Is there a way to do this more efficiently in Vim?

Here is an example of what a line in one of the files might look like:

S22Tg    K1B12N1Tg    D1AE22K5    K2B12N1Tg    D1AE22K6    W01B12N1Tg    D1AE22TDNXW01    W02B12N1Tg    D1AE22TDNXW02    W03B12N1Tg

Note, that the lines are all very similar and only differ in terms of the numbers occurring after the letters.

2 Answers 2

5

In Vim, you could limit your substitution to the lines that contain NX:

:g/NX/s/N1/NX/

Preceding the substitution with /NX/ makes Vim perform it only on the next line that contains NX (using ranges), and using :g makes it run on all lines that match NX.

1

You don't necessarily need to open the file in vim to do this. You can do it on the command line sed '/NX/s/N1/NX/g' <filename> >> <newfilename> and then rename the <newfilename> to the original file.

1
  • Thank you. I eventually opted for the pure vim solution as this was the focus of the question! Commented Apr 5, 2015 at 9:42

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.