[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash script - pass command line arg to embedded sed script with multiple args



* 2010-04-17 09:34 (-0700), Michael Elkins wrote:

> You can run into that sort of problem if your pattern to replace
> contains any forward slashes (/) in it.  If you need to such an
> expansion, you probably want to do it in two passes, first doing a / to
> \/ substitution on your replacement strings, then inserting them into
> your final expression:
>
> pata=`echo $1 | sed 's,/,\/,'`
> patb=`echo $2 | sed 's,/,\/,'`
> sed -e "s/PATTERN1/$pata/" -e "s/PATTERN2/$patb/" < input > output

There are more special characters which may need escaping. The following
example may be unnecessarily verbose for a throw-away script but it
tries to address the escaping problem properly and adds some
abstraction.


    #!/bin/sh
    
    input="input"
    output="output"
    sub1=$1
    sub2=$2

    quote_basic_regexp ()   { sed -e 's,[][\^$.*],\\&,g'; }
    quote_replace_string () { sed -e 's,[&\],\\&,g'; }
    quote_solidus ()        { sed -e 's,/,\\&,g'; }

    replace_literal_string () {
        local regexp=$(printf '%s\n' "$1" | quote_basic_regexp | \
            quote_solidus)
        local replace=$(printf '%s\n' "$2" | quote_replace_string | \
            quote_solidus)
        sed -e "s/$regexp/$replace/g"
    }

    replace_literal_string PLACEHOLDER1 "$sub1" < "$input" | \
        replace_literal_string PLACEHOLDER2 "$sub2" > "$output"


-- 
Feel free to Cc me your replies if you want to make sure I'll notice
them. I can't read all the list mail.


Reply to: