2

Would like to ask because I'm having an issue with sed command in unix scripting.

#!/bin/sh
cnt=2
sed '1 c\
$cnt' test.txt

I want to replace the first line of text file test.txt with the value of variable cnt which is 2. How can I pass the variable on the above sed command? The sed command treats $cnt as string.

user3051523
  • 45
  • 1
  • 2
  • 5

2 Answers2

5

Variables are not expanded in single quotes. They are expanded in double quotes, though.

sed "1 c\\
$cnt" test.txt

Note that sed doesn't update the input file by default, it outputs the changed version instead. If your implementation of sed supports it, use the -i switch to modify the input file. Otherwise, you'd have to redirect the output to a new file and rename it back to the original name:

sed "..." text.txt > text.new
mv text.new text.txt
choroba
  • 231,213
  • 25
  • 204
  • 289
1

Change to:

#!/bin/sh
cnt=2
sed "1 c\
$cnt" test.txt

For variable interpolation to happen, u need to put it within double quotes rather than single quotes.

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27