Jega B
Jega B

Reputation: 35

Variables not working in sed command

How to use a variable instead of 3 in the command below?

sed -i '3s/$/ newvalue/' filename

I tried

var=1
sed -i '$vars/$/ newvalue/' filename
sed -i "$vars/$/ newvalue/" filename

Upvotes: 0

Views: 2298

Answers (1)

randomir
randomir

Reputation: 18687

First, you need to use double quotes to allow shell parameters/variables to expand. Then, you need to use braces to isolate the variable name if text that follows the variable could be interpreted as part of variable name (before${var}after). Finally, to use literal $ under double quotes, you should escape it a blackslash. All together:

var=3
sed -i "${var}s/\$/ newvalue/" filename

One alternative is to use alternating double and single quotes (under which no character is treated specially, including $ for parameter expansion):

sed -i "$var"'s/$/ newvalue/' filename

Upvotes: 5

Related Questions