2

In below example, I can use the literal newline characters to add an empty line before and after 3. Is it possible to use \n instead? I'm using Gnu sed 4.5.

root@u1804:~# seq 5 | sed -r -e '/3/{i\
> ' -e 'a\
> ' -e '}'
1
2

3

4
5
root@u1804:~#
  • Haha, sorry to bother you again. I'm learning sed right now and I just want to make the command a little bit cleaner. If I can use \n instead of a literal newline, I can write the command in a single line, which will make it easy to type and read. – Just a learner Jan 6 at 23:38
5

If you use \n it will work but you'll end up with two newlines before and after as the commands i\ and a\ already add a newline before and respectively after the pattern space is printed so

seq 5 | sed  -e '3i\\n' -e '3a\\n'

prints

1
2


3


4
5

If, for some reason, you want it in one-line you can use multiple -expressions:

seq 5 | sed  -e '3{i\' -e '' -e 'a\' -e '' -e '}'

though in this case it's easier/shorter to just use the hold space:

 seq 5 | sed  '3{G;H;x;}'
  • 1
    ... or (with GNU sed) {G;H;z;x;} if you need the hold space to be returned to its initial - empty - state after – steeldriver Jan 7 at 0:49

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.