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.

2 Answers 2


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
    Commented Jul 4, 2019 at 13:55
  • @In78 see my update. Next time, that is helpful information to add in the question.
    – D. Ben Knoble
    Commented Jul 4, 2019 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
    Commented Jul 4, 2019 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
    Commented Jul 4, 2019 at 15:24
  • yeah this will work
    – In78
    Commented Jul 4, 2019 at 20:17

I know this is late & maybe I am misunderstanding the requirements, but you can do this in POSIX ex, without vim extensions.

Simply (a)ppend any text following a match, optionally with a number of additional lines. The . is not a typo, you need that to exit the append.

For this overly complex example, ^H is CTL+v,CTL+h (i.e. col -b)

LANG=C ex -s <<'EOF'
r!man true
g/.^H/ s///g
"%!sed "s/.`printf '\b'`//g"
wq! true.txt

The extras are just to give you some other ideas. /pattern/+1i would do the same thing, but (i)nsert before, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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