Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed Insert Multiple Lines

Tags:

shell

sed

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

like image 716
Pez Cuckow Avatar asked Sep 03 '12 14:09

Pez Cuckow


1 Answers

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
like image 126
Gilles 'SO- stop being evil' Avatar answered Sep 22 '22 19:09

Gilles 'SO- stop being evil'