Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The file has the content:

[Greet]

Hello
Hi
Hola

I want to add a string called Hey so that its position is after Hello:

[Greet]

Hello
Hey
Hi
Hola

Is there a way to do the above by using echo or other native linux tools from the command line?

share|improve this question
up vote 3 down vote accepted

Use sed.

Since the sed command to insert or append lines requires a line break it is easiest to place the sed command in a file and tell sed to execute that file.

Example: to insert Hey after (every) Hello, create the following file:

/Hello/a\
Hey

Then invoke sed:

sed -f appendheyafterhello.sed < sourcefile > resultfile

Here are more sed commands including how to insert a line before a pattern or at a specific line number.

share|improve this answer

Here's some perl solutions:

perl -p -i -e 'print "Hey\n" if /Hi/'  filename

or

perl -p -i -e 'print "Hey\n" if $. == 4'  filename

or

perl -n -i -e 'print; print "Hey\n" if /Hello/' filename
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .