简体   繁体   中英

How to pass output of grep to sed?

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

如果打算打印grep返回的行,生成sed脚本可能是要走的路:

grep -E -o '[0-9]+' error | sed 's/$/p/' | sed -f - error

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

Yes you can pass output from grep to sed.

Please note that in order to match whole numbers you need to use [0-9]* not only [0-9] which would match only a single digit.

Also note you should use double quotes to get variables expanded(in the sed argument) and it seems you have a typo in the second variable name.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM