Linux 使用 awk 从文本文件中提取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6997767/
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-05 05:36:02  来源:igfitidea点击:

Extracting data from a text file using awk

linuxsedawk

提问by Graham Bell

Possible Duplicate:
Extract data between two points in a text file

可能的重复:
提取文本文件中两点之间的数据

For example:

例如:

Reply: [200/OK] bytes=29086 time=583ms

I would want to extract the value between "time=" and "ms"

我想提取“time=”和“ms”之间的值

Expected Result:

预期结果:

"583"

“583”

回答by miku

Ugly but works:

丑陋但有效:

$ echo "Reply: [200/OK] bytes=29086 time=583ms" | 
    awk '{print '} | sed -e 's/[a-z=]//g'
583

Or without sed:

或者没有sed

$ echo "Reply: [200/OK] bytes=29086 time=583ms" | 
    awk '{ split(,a,"="); gsub(/ms/,"", a[2]); print a[2] }'
583

回答by shellter

Try this

尝试这个

printf "Reply: [200/OK] bytes=29086 time=583ms\n" \
| awk '/^Reply:/{sub(/^.*time=/,"",
echo "Reply: [200/OK] bytes=29086 time=583ms" | sed "s/.*time=\(.*\)ms//"
) ;sub(/ms$/,"",
echo "Reply: [200/OK] bytes=29086 time=583ms" | awk -F'time=|ms' '{print }'
); print
echo "Reply: [200/OK] bytes=29086 time=583ms" | sed 's/.*time=\([0-9]*\)ms.*//'
}'

I hope this helps.

我希望这有帮助。

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

PS,因为您似乎是新用户,如果您得到的答案对您有帮助,请记住将其标记为已接受,和/或给它一个 +(或 -)作为有用的答案。

回答by Paul

##代码##

回答by Micha? ?rajer

I would use sed for that, but since you ask for awk:

我会使用 sed ,但既然你要求 awk:

##代码##

The -Fdefines extended regexp for field separator. So we define that "time=" or "ms" separates the fields, and then print second field.

-F定义延长字段分隔符的regexp。所以我们定义“time=”或“ms”分隔字段,然后打印第二个字段。

using sed, it would be:

使用 sed,它将是:

##代码##