Linux 提取同一行特定单词后的一个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17371197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract one word after a specific word on the same line
提问by Rahul
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:
如何在 Linux (csh) 中提取特定单词之后的单词?更准确地说,我有一个文件,其中有一行,如下所示:
[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?
我想提取单词100
后面的数字--pe_cnt
。我不能使用 sed,因为它只有在您想提取整行时才有效。也许我可以使用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.
此外,我有多个具有不同值的文件,而不是100
因此我需要提取值但不依赖于值的东西。
采纳答案by jaypal singh
With awk
:
与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
:
grep -oP "(?<=--pe_cnt )[^ ]+" inputFile
回答by ctn
You can use sed. Just make a group of want you want to match and replace the whole line with the group:
您可以使用 sed。只需创建一组想要匹配的内容并将整行替换为该组:
sed -n 's/^.*pe_cnt\s\+\([0-9]\+\).*$//p' file
回答by iruvar
If there is a single-space character between --pe_cnt
and 100
, you may be able to use lookahead and lookbehind assertions
如果--pe_cnt
和之间有一个单空格字符100
,您可以使用先行和后行断言
grep -oP '(?<=--pe_cnt\s)\d+(?=\s+--rd_cnt)'