问题
I am using this command in a shell script
lnum=5
str="Hello foo"
filename="/path/fiename"
sed -i "$lnum i $str" $filename
Getting the following error
sed: -e expression #1, char 3: : doesn't want any addresses
I had used this command before for other script it worked fine, the only change i made this time is file-name has a path to the file, but I tried it with just giving file-name and not the path by getting into the path and executing the script but still it doesn't work
I am unable to resolve it can anybody help
回答1:
If you are using OSX , BSD (and AIX) versions of sed
, the backup extension for the -i
in place editing flag is not optional.
GNU sed
differs on this I believe, so the script may work on Linux.
This is a bit of a pain for portability - but it gets worse with "in-place" editing when BSD derived sed
is used. This version of sed
is arguably more "standard" in some ways (as in: "lowest common denominator across POSIX systems") but this behaviour seems like a bug:
sed: 1: "5 i hello foo": command i expects \ followed by text
Here is how I made your script work on several BSD flavors:
lnum="5"
str="Hello foo"
filename="sed-mess.txt"
sed -i "" "$lnum i\^M
$str" $filename
I had to enter a literal line end character with Ctrl-v [Return]
to get the i
command to work since \
is required and has to have nothing following it. Not sure how GNU sed
would handle this.
Can you use perl
? ;-)
回答2:
The old farts use ed for this type of problem:
cat /tmp/sample
#!/bin/ksh
lnum=5
str="Hello bar"
filename="/tmp/foo"
ed - $filename <<EOF
$lnum
i
$str
.
w
q
EOF
cat /tmp/foo
line
line
line
line
line
line
line
line
line
wc /tmp/foo
9 9 45 /tmp/foo
/tmp/sample
line
wc /tmp/foo
10 11 55 /tmp/foo
cat /tmp/foo
line
line
line
line
Hello bar
line
line
line
line
line
i
is "insert" before while a
is "append" after. I don't know what the sed i command does exactly but I would expect it would be the same as i
Hope this helps
来源:https://stackoverflow.com/questions/17470697/getting-an-error-with-sed-expression