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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:21:01  来源:igfitidea点击:

Extract one word after a specific word on the same line

linuxbashcsh

提问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 100which is after the --pe_cntword. 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 100so 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_cntand 100, you may be able to use lookahead and lookbehind assertions

如果--pe_cnt和之间有一个单空格字符100,您可以使用先行和后行断言

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