问题
I'm trying to do an insert with sed (having just read up on it) and i'm being stumped by trying to insert multiple lines?
What i'm currently doing is:
sed -i "${line} i\
/* Name - ID */ \
select @ID = NULL \
from Animals \
where VrsnID = @VrsnID \
and Request= \"Request\" \
\
" animalNames.txt
Note echo $line
== 131
New Problem
Everything appears on one line in the output? (also missing the first indent)
/* Name - ID */ select @ID = NULL from Animals where VrsnID = @VrsnID and Request= "Request"
Resolved
But this throws:
sed: -e expression #1, char 47: unknown command: `
'
Any idea why?
Thanks for your time
回答1:
For the new trouble :
Use double backslash \\
回答2:
In a shell script, backslash+newline expands to nothing. It's a way to continue to the next line without actually having a newline in the string. So what sed sees is just one big line. Compare:
$ echo "foo\
> bar"
foobar
$ echo "foo
> bar"
foo
bar
You need to pass a backslash and a newline to sed, so escape the backslash by putting another backslash before it.
sed -i "${line} i\\
/* Name - ID */ \\
select @ID = NULL \\
from Animals \\
where VrsnID = @VrsnID \\
and Request= \"Request\" \\
" animalNames.txt
This may be more readable if you pass the script on the standard input as a here document. You need to leave expansion on to substitute ${line}
, so you still need to double the backslash.
sed -i -f - animalNames.txt <<EOF
${line} i\\
/* Name - ID */ \\
select @ID = NULL \\
from Animals \\
where VrsnID = @VrsnID \\
and Request= "Request" \\
EOF
回答3:
This might work for you:
sed ${line}'i\
/* Name - ID */ \
select @ID = NULL \
from Animals \
where VrsnID = @VrsnID \
and Request= \"Request\"
' animalNames.txt
来源:https://stackoverflow.com/questions/12249509/sed-insert-multiple-lines