Replace a word with multiple lines using sed?

前端 未结 9 1623
礼貌的吻别
礼貌的吻别 2020-11-27 06:32

I\'m working on a bash-script that has to prepare an E-Mail for being sent to a user.

It aggregates some data, which ends up being multiple lines of stuff. For the e

相关标签:
9条回答
  • 2020-11-27 06:55

    Echo variable into temporary text file.

    Insert text file into mail.tpl and delete data from mail.tpl

    echo ${DATA} > temp.txt    
    sed -i -e "/_data_/r temp.txt" -e "//d" mail.tpl
    
    0 讨论(0)
  • 2020-11-27 06:56

    If you build your multiple line text with "\n"s, this will work with a simple sed command as:

    DATA=`echo ${DATA} | tr '\n' "\\n"`
    #now, DATA="line1\nline2\nline3"
    sed "s/_data_/${DATA}/" mail.tpl
    
    0 讨论(0)
  • 2020-11-27 06:57

    Not sure if you have tried to put "\n" in the replace part

    sed 's/[pattern]/\
    [line 1]\n\
    [line 2]\n\
    [line n]\n\
    /g' mail.tpl
    

    The first line has /\ for readibility reasons. Each line after that is a stand-alone line like you would find in a text editor. Last line is stand-alone, once again for readability reasons. You can make all of this one line if needed. Works on Debian Jessie when I tested it.

    0 讨论(0)
  • 2020-11-27 07:00

    You can put your data in a temp file and run:

    $ sed '/_data_/r DATA_FILE' mail.tpl | sed '/_data_/d'> temp; mv temp mail.tpl
    
    0 讨论(0)
  • 2020-11-27 07:01

    I tried it and sed 's/pattern/\na\nb\nc/g' but it does not work on all systems. What does work is putting a \ followed by a newline in the replace pattern, like this:

    sed 's/pattern/a\
    b\
    c/g'
    

    This appends a line containing b and a line containing c when the pattern is seen.

    To put it in a variable, use double backslashes:

    export DATA="\\
    a\\
    b\\
    c"
    

    and then:

    sed "s/pattern/${DATA}/g"
    

    Note the double quotes.

    0 讨论(0)
  • 2020-11-27 07:04

    Escaping all the newlines with a \ (except the last one) worked for me. The last newline must not be escaped not to break the s command.

    Example :

    DATA="a
    b
    c"
    
    ESCAPED=$(echo "${DATA}" | sed '$!s@$@\\@g')
    echo "${ESCAPED}" 
    a\
    b\
    c
    
    sed "s/pattern/${ESCAPED}/" file
    
    0 讨论(0)
提交回复
热议问题