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.
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
.
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
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. :)
sed
command to do? When the shell has finished expanding$v/d
, you have an invalidsed
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 usesed "/$v/d"
. If you're looking for lines 1 to the first line containingpop
, you've got to do work on the value in$v
to generatesed "1,/pop/d"
. If you want to do something else, you need to describe what it is you do want.