Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitution with sed + bash function

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

like image 507
Samir Boulil Avatar asked Apr 25 '11 09:04

Samir Boulil


People also ask

Can you use sed in a bash script?

We can manipulate text in streams and files using sed from the command line in Bash and other command-line shells.

What does sed do in bash?

Sed is a non-interactive [1] stream editor. It receives text input, whether from stdin or from a file, performs certain operations on specified lines of the input, one line at a time, then outputs the result to stdout or to a file. Within a shell script, sed is usually one of several tool components in a pipe.

What is sed s /\ g?

The sed expression s/~/ /g replaces every tilde with a space character. It means, literally, "substitute everything that matches the regular expression ~ with a space, globally (on the whole input line)".


2 Answers

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
like image 177
xiaofengmanlou Avatar answered Oct 17 '22 12:10

xiaofengmanlou


Agree with Glenn Jackman. If you want to use bash function in sed, something like this :

sed -rn 's/^([[:digit:].]+)/`date -d @&`/p' file |
while read -r line; do
    eval echo "$line"
done

My file here begins with a unix timestamp (e.g. 1362407133.936).

like image 21
Antonio Avatar answered Oct 17 '22 13:10

Antonio