0

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
randomir
  • 17,989
  • 1
  • 40
  • 55
Jega B
  • 35
  • 2
  • 12
  • Possible duplicate of [Replace a string in shell script using a variable](https://stackoverflow.com/questions/3306007/replace-a-string-in-shell-script-using-a-variable) – Wiktor Stribiżew Jul 21 '19 at 12:59

1 Answers1

4

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
randomir
  • 17,989
  • 1
  • 40
  • 55
  • Hmm, it seems that `sed "${var}s/$/ newvalue/" filename` works fine too without the escape before `$` – etopylight Nov 20 '17 at 08:46
  • 1
    It works in this case because "/" that follows is not a valid variable name. But in general, you should escape "$" under double quotes. Have in mind valid variable names are not just alphanumeric strings, but also special shell variables, like ?, !, #, etc. – randomir Nov 20 '17 at 08:57
  • 1
    That's definitely a more safer syntax, thanks for the explanation. – etopylight Nov 20 '17 at 09:02
  • 1
    @ randomir : thanks its working . sed -i "${var}s/\$/ newvalue/" – Jega B Nov 20 '17 at 13:19
  • One more query., please help !! How to remove blank space from end of the file? – Jega B Nov 20 '17 at 15:49
  • @JegaB, what kind of blank space, blank lines? You can try with `sed -i '/^[[:space:]]*$/d' file`. This will remove *all* lines with only whitespace characters (but not only at the end of file). – randomir Nov 20 '17 at 16:09
  • 1
    @ randomir : Thank you soo much.. your solution solved my problem. – Jega B Nov 21 '17 at 03:31