Sed Insert Multiple Lines

ぐ巨炮叔叔 提交于 2021-02-16 10:23:15

问题


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

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