4

Given a sed expression (and GNU sed 4.2.2 on ArchLinux)

/match/i\tline1\n\tline2

which should insert two tab-indented lines above the match, I find that the escaping of the first character (in the example, \t) is ignored but all other escaped characters are treated correctly.

Testing this like this:

echo match | sed -e '/match/i\tline1\n\tline2'

results in

tline1
    line2
match

It doesn't matter what the initial escaped character is (e.g. tab or newline) the result is the same. What is the correct way to consrtuct the expression so that the first character is treated correctly?

5

Check the gnu sed manual (http://www.gnu.org/software/sed/manual/html_node/Other-Commands.html#Other-Commands) -- the i command is actually the i\ command, so you just need an extra backslash

echo match | sed -e '/match/i\\tline1\n\tline2'
# ---------------------------^
1
  • wierd, I am sure I tried that but yes, you're right :)
    – starfry
    May 9 '13 at 17:51
3

The standard syntax (in case you want to be portable to non-GNU systems) is:

sed 'i\
\   line1\
line2'

That is, you need a newline after i\, and there's no escape sequence recognised (above the tab character is entered literally). Only, you need to escape the newline, backslash characters and leading blanks¹ with a backslash.

With shells that support the (non-standard sh) ksh $'...' type of quotes (like ksh93, zsh or bash), you can write it:

sed $'i\\\n\\\tline1\\\nline2'

¹ backslashes are not needed before leading blanks in POSIX compliant seds, but some implementations like on BSDs would still strip those leading blanks without the backslash.

1

I was going to suggest:

 echo match | sed -e 's/match/\tline1\n\tline2\n&/'
1
  • OK, but the OP said that echo match | … was just for testing. To obtain the behavior that /match/i… seems to be looking for, you would need 's/.*match/\tline1\n\tline2\n&/'.
    – Scott
    Jul 29 '14 at 0:47

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.