Extract one word after a specific word on the same line

徘徊边缘 提交于 2019-11-26 07:48:04

问题


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 want to 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.


回答1:


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



回答2:


You can use sed. Just make a group of want you want to match and replace the whole line with the group:

sed -n 's/^.*pe_cnt\s\+\([0-9]\+\).*$/\1/p' file



回答3:


If there is a single-space character between --pe_cnt and 100, you may be able to use lookahead and lookbehind assertions

grep -oP '(?<=--pe_cnt\s)\d+(?=\s+--rd_cnt)'


来源:https://stackoverflow.com/questions/17371197/extract-one-word-after-a-specific-word-on-the-same-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!