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


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


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?

3 Answers 3


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'
# ---------------------------^
  • wierd, I am sure I tried that but yes, you're right :)
    – starfry
    Commented May 9, 2013 at 17:51

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

sed 'i\
\   line1\

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.


I was going to suggest:

 echo match | sed -e 's/match/\tline1\n\tline2\n&/'
  • 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&/'. Commented Jul 29, 2014 at 0:47

You must log in to answer this question.

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