Use of bash program with argument inside a sed

I have a small SED question to ask you. But first of all, I know there are other ways to do what I want (I've already made a small python script to do that), but for my own curiosity, I'd like to know if there is a way to do that with SED.

So, e.g. : here is a CSV file like :

12345678,yan solo
23456789,luke skywalker
34567890,leia organa

And here is a bash script named "SOMESCRIPT", which will transform a argument in something else. E.g. :

~$ ./SOMESCRIPT 12345678

So, what I'd like to di is : use that script from inside a SED to regenerate the CSV with converted value.

Here an example of output :

abcd,yan solo
efgh,luke skywalker
ijkl,leia organa

Some thinkings :

~$ cat somecsv.csv | sed "s/\(.*\),/\1/g"

--> The regex catch the part to be transformed and save it to the stack in \1

~$ cat somecsv.csv | sed "s/\(.*\),/`SOMESCRIPT `\1/g"

--> For each line, SOMESCRIPT is executed, but before the printing of \1

~$ cat somecsv.csv | sed "s/\(.*\),/`SOMESCRIPT \1`/g"

--> For each line, SOMESCRIPT is executed, but \1 is not recognized as a shell variable

So, basicaly, the question is : is it possible to pass the stack value \1 as a shell argument to SOMESCRIPT ?


This might work for you (GNU sed):

sed 's/\(.*\)\(,.*\)/printf "%s\2\\n" $(SOMESCRIPT "\1")/e' file

This uses the GNU specific e flag/command. If you remove it from the substitution command the output from sed command can be piped into a bash command which does the same thing.

With GNU sed you can pass the e option to s command which makes sed execute the result of the substitution as a shell command:

sed 's#.*#./SOMESCRIPT "\0"#e'

You can also use awk for the job. From within an awk program you can use the system() function to execute an external command through a shell:

awk -F, '{system("./SOMESCRIPT \""$1"\"")}'

The shell itself can also do it:

while IFS="," read a b c ; do
    ./SOMESCRIPT "$a"
done < some.csv

After all I favour the shell solution since it properly escapes the argument of SOMESCRIPT - by design.

Need Your Help

to get URL address

java url

how to get URL address while every time page is refreshed in java..?

Storing user_id in the paper_trail versions table

ruby-on-rails-3 audit-trail paper-trail-gem

I am using paper trail to audit changes to data and would like to store the user_id of the current user in addition to the "whodunnit" column that paper_trail stores by default.