user9526185
user9526185

Reputation:

Newline between variables in sed

I'm trying to print two variables at the top of a text file. I have variables:

file=someFile.txt
var1=DONKEY
var2=KONG
sed -i "1s/^/$var1$var2/" $file

The output of the last line is: DONKEYKONG While i need it to be:

DONKEY KONG

I tried:

sed -i "1s/^/$var1\n$var2/" $file

sed -i "1s/^/$var1/\n$var2/" $file

sed -i "1s/^/$var1/g $file

sed -i "2s/^/$var2/g $file

However, none of those worked.

EDIT: I tried $var1\\n$var2, opened the file in notepad and it didn't look right. I opened in notepad++ & sublime and it was the right formatting

Upvotes: 3

Views: 82

Answers (3)

Rob Davis
Rob Davis

Reputation: 15802

Two approaches:

1) Include newlines in the command by escaping them with backslashes:

sed -i -e "1s/^/${var1}\\
${var2}\\
/" "$file"

Make sure \\ is followed immediately by a newline, no other white space.

Or, 2) avoid the newline escaping issue and take advantage of sed's ability to insert newlines around its hold space:

sed -i -e "1h;1s/.*/${var2}/;1G;1h;1s/.*/${var1}/;1G" "$file"

To explain this second approach, the commands do the following:

h: copy the first line to the hold space
s: replace the first line with the contents of var2
G: append the hold space to the pattern space with a newline separator

After this we've inserted var2 above line 1, on its own line.
Repeat h, s, and G with var1.
Apply all commands to line 1, no other lines.

Upvotes: 0

Walter A
Walter A

Reputation: 20032

With ed:

printf "%s\n" 1 i "$var1" "$var2" "." w q | ed -s "$file"

Upvotes: 1

Barmar
Barmar

Reputation: 782508

Put a literal newline in the replacement string. You also need to escape it.

sed -i "1s/^/$var1\\
$var2/" $file

Upvotes: 1

Related Questions