Getting an error with sed expression

时间秒杀一切 提交于 2020-01-17 01:10:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!