I need to search for a string in a file, then I need to some text after one line following the first match. I need to perform this for a number of files in a script.

I am trying to use vim ex mode for this. I know :/search_string can perform a search but I am not able to figure out how to move the cursor down and insert the line. Will sed or awk be more suitable for this?

I need to do this in a script.


Load your files into vim:

vim files

Then, we will use a command on each of them via :argdo. The command searches (:/pattern/+1) and opens a new line:

:/pattern/+1 normal! oYour new text here

Another option is to put from the expression register

:/pattern/+1 put ='Your text here'


argdo /pattern/+1 put ='text'

This may struggle if any of the files don’t contain pattern.

From my answer on scripting ex:

ex file <<EOF
/pattern/+1 put ='text'
  • I need to do this in a script.
    – In78
    Jul 4 '19 at 13:55
  • @In78 see my update. Next time, that is helpful information to add in the question.
    – D. Ben Knoble
    Jul 4 '19 at 14:22
  • I also need to add the text after one line following the match. Sorry for not being clearer in my question.
    – In78
    Jul 4 '19 at 15:02
  • 1
    @ln78 can you provide some sample input/output? this answer puts the text on the line following the pattern. Do you mean the line following the line following the pattern? If so, try /pattern/+1 put ='text'
    – D. Ben Knoble
    Jul 4 '19 at 15:24
  • yeah this will work
    – In78
    Jul 4 '19 at 20:17

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.