Search code examples
bashsed

how to preserve all spacing with 'sed' when inserting content in a file


I have a shell variable with the following content:

Var="    a b   c"

and the following ASCII file 'file.txt'

line-1
line-2
line-3

I would like to insert the content of $Var after the 2nd line in the file using 'sed' but preserve all spacings. I.e. I want to end up with:

line-1
line-2
    a b   c
line-3

However, 'sed' doesn't preserve spacing at the beginning, and produces:

line-1
line-2
a b   c
line-3

What do I need to modify in the command input so that 'sed' also preserves spacings at the beginning? This is what I tried and this failed:

sed -i "2i $Var" file.txt
sed -i "2i\\$Var" file.txt

Solution

  • According to the sed documentation:

    • a\ - Appending text after a line.
    • i\ - Immediately output the lines of text which follow this command.

    You could use 2a instead of 2i to append the line after the second line.

    sed -i "2a\\$Var" file.txt
    

    The contents of file.txt afterwards:

    line-1
    line-2
        a b   c
    line-3