I'm writing a Bash script and when inserting lines to a file using GNU sed, the first new line is inserted as a literal n, while the rest is inserted as new lines. The command is this:

sed '5i\n\n\n' myfile

The output is this:


As seen, the first line in the output contains an "n" where it should be none, what am I missing about this behavior? is it possible to make sed insert only new lines with '\n'? Thank you.

  • Add a sample of the file that you are working with and the expected output to your question. – Nasir Riley Jul 22 at 6:02

The standard sed insertion is

text here...

(including the backslash). GNU sed has an extension that accepts the text on the same line as the i command, but if there's a backslash after the i it's interpreted as ending the command as usual - though it still doesn't force you to move to a new line, either. You can use


to do both together. This is not an escaped backslash, but two different kinds of backslash right next to each other. This behaviour doesn't seem to be documented, but is consistent across commands and versions.

You might find it clearer to use another GNU extension:

sed -e '5i\' -e '\n\n\n'

with the command and text split across two -e arguments to avoid that ambiguity.

  • You actually don't need the third \n. A new line is automatically added at the 5th line so only two of the \n are needed. Three of them effectively adds four new lines. – Nasir Riley Jul 22 at 5:56
  • To be honest, I'm not really clear on how many are actually wanted - this will insert all three \ns and result in four blank lines, which matches one part of the question and not the other. They can be removed (or added) as required to match expectations. – Michael Homer Jul 22 at 6:00
  • It seems like only three new lines are wanted at the fifth line but I've asked the questionner to add the contents of the file and expected output so it's clearer. Your answer does work but that info may help to understand how it may need to be altered to get the exact output that's wanted. – Nasir Riley Jul 22 at 6:06
  • 2
    @NasirRiley No it's cool, thanks, I already accepted this answer, no need to check the code itself, the answer works perfect. – Juli TR Jul 22 at 6:36
  • 1
    @MichaelHomer Thanks for the answer, really opportune and to the point. – Juli TR Jul 22 at 6:36

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