Substitution with sed + bash function

Samir Boulil picture Samir Boulil · Apr 25, 2011 · Viewed 11.6k times · Source

my question seems to be general, but i can't find any answers.

In sed command, how can you replace the substitution pattern by a value returned by a simple bash function.

For instance, I created the following function :

function parseDates(){
    #Some process here with $1 (the pattern found)
    return "dateParsed;
}

and the folowing sed command :

myCatFile=`sed -e "s/[0-3][0-9]\/[0-1][0-9]\/[0-9][0-9]/& parseDates &\}/p" myfile`

I found that the caracter '&' represents the current pattern found, i'd like it to be passed to my bash function and the whole pattern to be substituted by the pattern found +dateParsed.

Does anybody have an idea ? Thanks

Answer

xiaofengmanlou picture xiaofengmanlou · Apr 26, 2011

you can use the "e" option in sed command like this:

cat t.sh

myecho() {
        echo ">>hello,$1<<"
}
export -f myecho
sed -e "s/.*/myecho &/e" <<END
ni
END

you can see the result without "e":

cat t.sh

myecho() {
        echo ">>hello,$1<<"
}
export -f myecho
sed -e "s/.*/myecho &/" <<END
ni
END