Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed insert line with spaces to a specific line

Tags:

linux

bash

sed

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 
like image 860
Yo Al Avatar asked Aug 26 '13 08:08

Yo Al


People also ask

How do you put a space in a line using sed?

We've learned that sed's “a” and “i” commands can insert or append a new line. The backslash character after the “a” or “i” command doesn't function as the part of an escape sequence, such as \t as a tab or \n as a newline. Instead, it indicates the beginning of the text in the new line we're inserting.


1 Answers

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" 
like image 96
Atropo Avatar answered Sep 23 '22 14:09

Atropo