1

I want to replace a string in a line of a document, with sed. Where the LINE Number value should come from a variable, $var.

I've tried:

sed '%ds/peer/md5/g' $var ./temp.txt

but it gives

sed: -e expression #1, char 1: unknown command: `%'

Also tried:

sed -e '"$var"s/peer/md5/g'-i ./temp.txt
sed: -e expression #1, char 1: unknown command: `"'

Finally tried:

printf '%ds/peer/md5/g;\n' 80 | sed -f - ./temp.txt

which prints correctly, but I can't save the result file with output redirection (>) or -i command.

2 Answers2

1

I realized that the correct way is:

sed "$var"'s/string1/string2/' -i ./temp.txt

where var is the variable that have the line number of the file.

0
  1. sed -i.bak "s/existing_string/$new_string/g" ./temp.txt
  2. sed -i.bak "s/$existing_string/new_string/g" ./temp.txt

Here $ is used for your variable, in sed remember to use " " while using variables within it.

The option -i.bak will create backup file of original.

AdminBee
  • 22,803