Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to preserve all spacings with 'sed' when inserting content in the 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks!

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading