Pez Cuckow
Pez Cuckow

Reputation: 14412

Sed Insert Multiple Lines

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

Upvotes: 9

Views: 21265

Answers (3)

potong
potong

Reputation: 58410

This might work for you:

sed ${line}'i\
    /* Name - ID */ \
    select  @ID = NULL \
    from    Animals \
    where   VrsnID = @VrsnID \
    and     Request= \"Request\"

' animalNames.txt

Upvotes: 1

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

Upvotes: 15

Zulu
Zulu

Reputation: 9275

For the new trouble : Use double backslash \\

Upvotes: 8

Related Questions