Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass output of grep to sed?

Tags:

bash

shell

ubuntu

I have a command like this :

cat error | grep -o [0-9]

which is printing only numbers like 2,30 and so on. Now I wish to pass this number to sed.

Something like :

cat error | grep -o [0-9] | sed -n '$OutPutFromGrep,$OutPutFromGrepp'

Is it possible to do so?

I'm new to shell scripting. Thanks in advance

like image 360
batman Avatar asked Sep 05 '12 07:09

batman


2 Answers

If the intention is to print the lines that grep returns, generating a sed script might be the way to go:

grep -E -o '[0-9]+' error | sed 's/$/p/' | sed -f - error
like image 171
Thor Avatar answered Sep 27 '22 22:09

Thor


You are probably looking for xargs, particularly the -I option:

themel@eristoteles:~$ xargs -I FOO echo once FOO, twice FOO
hi
once hi, twice hi
there
once there, twice there

Your example:

themel@eristoteles:~$ cat error
error in line 123
error in line 234
errors in line 345 and 346
themel@eristoteles:~$ grep -o '[0-9]*' < error | xargs -I OutPutFromGrep echo sed -n 'OutPutFromGrep,OutPutFromGrepp'
sed -n 123,123p
sed -n 234,234p
sed -n 345,345p
sed -n 346,346p

For real-world use, you'll probably want to pass sed an input file and remove the echo.

(Fixed your UUOC, by the way. )

like image 29
themel Avatar answered Sep 27 '22 23:09

themel