Passing a variable to sed command

Hi guys,

I wanted to pass a variable to the sed command which tells which line to be deleted.

a=2;
echo $a;
sed '$ad' c.out

it is throwing an error.

sed: 0602-403 "$a"d is not a recognized function.

I even tried "$a" and \$a.. but it is of no use.

Can you please correct me where i am going wrong.

Thanks,
Magesh.

Hi.

You should enclose the variable in braces: ${a} - and use double quotes for your sed.

Cheers

wc Test
      20      68     452 Test

a=2
sed "${a}d" Test | wc
      19      63     431

 export a=2;sed "${a}d" file

cool man.. i missed the double quotes.. But usually sed will use only single quotes, please correct me if i am wrong, then when we should use double quotes??

Yes, you're wrong :slight_smile:

You can use either, but if you're using variables, or anything that the shell needs to expand you should use double quotes.

sed "/${a}/d" c.out

Thanks.. for the explanation..
finally the code which worked is

sed "${a}d" c.out