1

Suppose I have a file which contains:

TEMP=100
TEMP=100

and I want to change all of the string beyond 'TEMP=' to 200, so it would read:

TEMP=200
TEMP=200

I could use the command :%s/TEMP=\zs.*/200/

What is the command I need to ensure that only the first instance gets changed? The result should read:

 TEMP=200
 TEMP=100

I have tried :s/TEMP=\zs.*/200/ but this fails unless I first perform :%s/TEMP=\zs.*/200/.

Many thanks!

4

That % in the %s command at the beginning of your command specifies a range and tells the command to be run for all lines (short for 1,$, where $ stands for the last line). Besides line numbers, you can also specify marks or even specify search items.

For the search you can specify the full range of regular expressions that vim knows about and you can even add offsets to it.

So for your use case, you want to replace from the first line until the search term TEMP is found, so you can use:

1,/^TEMP=/s/TEMP=\zs.*/200/

which will perform the :s command only between the first line and the first line found that starts with TEMP=.

For the details see :h :range and for a regular expression introduction have a look at :h 27.4 in the user manual.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.