sed insert line with spaces to a specific line

LinuxBashSed

Linux Problem Overview


I have a line with spaces in the start for example " Hello world". I want to insert this line to a specific line in a file. for example insert " hello world" to the next file

hello
world

result:

hello
    hello world
world

I am using this sed script:

sed -i "${line} i ${text}" $file

the problem is that i am getting my new line with out the spaces:

hello
hello world
world

Linux Solutions


Solution 1 - Linux

You can escape the space character, for example to add 2 spaces:

sed -i "${line} i \ \ ${text}" $file

Or you can do it in the definition of your text variable:

text="\ \ hello world"

Solution 2 - Linux

You only need one \ to input multiple blanks like this

sed -i "${line} i \    ${text}" $file

Solution 3 - Linux

$ a="  some string  "
$ echo -e "hello\nworld"
hello
world
$ echo -e "hello\nworld" | sed "/world/ s/.*/${a}.\n&/" 
hello
  some string  .
world

The . was added in the substitution above to demonstrate that the trailing whitepsaces are preserved. Use sed "/world/ s/.*/${a}\n&/" instead.

Solution 4 - Linux

It can be done by splitting the expression like this:

sed -i $file -e '2i\' -e "     $text"

This is a GNU extension for easier scripting.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYo AlView Question on Stackoverflow
Solution 1 - LinuxAtropoView Answer on Stackoverflow
Solution 2 - LinuxLeoChuView Answer on Stackoverflow
Solution 3 - LinuxdevnullView Answer on Stackoverflow
Solution 4 - LinuxdashohoxhaView Answer on Stackoverflow