1

I'm writing the following script:

v="1,pop";
sed "$v/d" dir/file1

It gives me this error:

char 3: unexpected `,'

How to solve this? Note: the value of $v cannot be controlled.

1
  • What are you expecting the sed command to do? When the shell has finished expanding $v/d, you have an invalid sed command. It might that you're wanting to delete lines that match what's in $v, in which case, to a first approximation, you should use sed "/$v/d". If you're looking for lines 1 to the first line containing pop, you've got to do work on the value in $v to generate sed "1,/pop/d". If you want to do something else, you need to describe what it is you do want. Jan 21, 2013 at 5:10

3 Answers 3

1

You are using sed in a wrong way.

$ v="1,pop";
$ cat file 
1,pop
Suku
JohnGeorge
stackoverflow
serverfault

$ sed '/'$v'/d' file
Suku
JohnGeorge
stackoverflow
serverfault

$ sed "/"$v"/d" file
Suku
JohnGeorge
stackoverflow
serverfault

If you want to substitute a bash variable inside sed, you need to surround it with quotes like I showed above. Also if you want to write modification to file, you need to use sed with -i.

1
  • The quoting above is wrong: sed /$v/d file, sed '/'$v'/d' file, and sed "/"$v"/d" file all do exactly the same thing, because none of the characters in quotes are shell metacharacters, and all quoting does is suppress the interpretation of metacharacters. Mind you, if $v contains (certain) metacharacters, you want it to be in double-quotes. Thus, sed "/$v/d" file is the recommended form. Jan 21, 2013 at 6:51
0

Using this way in script

v="1,pop"

sed "/^$v$/{

d

}" dir/file1

-1

You need the hashbang so your shell knows how to execute the script.

#!/bin/sh

Then you'll get...

sed: 1: "1,pop/d": expected context address

...which tells your the commands were executed. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.