Rahul Rahul - 4 years ago 129
Linux Question

Linux: extract one word after a specific word on the same line

I am a new Linux user and I'm self learned, so I'm sorry if this questtion is stupid. I did search online but couldn't find a proper answer..
How can I extract a word that comes after a specific word in Linux (csh)?
More precisely I have a file which has a single line which looks like this:

[some useless data] --pe_cnt 100 --rd_cnt 1000 [some more data]

I want to extract the number 100 which is after the --pe_cnt word.
I cannot use 'sed' as that works only if you wanna extract an entire line. Maybe I can use 'awk'?

Also, I have multiple files that have different values instead of 100 so I need something that extracts the value but doesn't depend on the value.

Answer Source

With awk:

awk '{for(i=1;i<=NF;i++) if ($i=="--pe_cnt") print $(i+1)}' inputFile

Basically loop over each word of the line. When you find the first you are looking for, grab the next word and print it.

With grep:

grep -oP "(?<=--pe_cnt )[^ ]+" inputFile
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download