How to pass output of grep to sed?

18,857

Solution 1

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

Solution 2

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. )

Share:
18,857
batman
Author by

batman

Updated on July 20, 2022

Comments

  • batman
    batman almost 2 years

    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

  • batman
    batman over 11 years
    +1 Nice. cat error | grep -o [0-9]+ After this I have the data, now how I can pass it to sed?