如何仅使用grep/sed提取子字符串和数字 [英] how to extract substring and numbers only using grep/sed

查看:57
本文介绍了如何仅使用grep/sed提取子字符串和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个同时包含文本和数字的文本文件,我想使用grep仅提取我需要的数字,例如,给定一个文件,如下所示:

I have a text file containing both text and numbers, I want to use grep to extract only the numbers I need for example, given a file as follow:

miss rate 0.21  
ipc 222  
stalls n shdmem 112

所以说我只想提取未命中率的数据,即 0.21 .我该如何使用grep或sed?另外,我需要一个以上的数字,不仅是 miss rate 之后的数字.也就是说,我可能想同时获得 0.21 112 .输出示例如下:

So say I only want to extract the data for miss rate which is 0.21. How do I do it with grep or sed? Plus, I need more than one number, not only the one after miss rate. That is, I may want to get both 0.21 and 112. A sample output might look like this:

0.21 222 112

因为我需要数据以备后用.

Cause I need the data for later plot.

推荐答案

请改用 awk :

awk '/^miss rate/ { print $3 }' yourfile

仅使用grep即可完成此操作,您需要使用非标准扩展名,例如此处使用PCRE(-P)和正向后置(?< = ..)且仅匹配(-o)的GNU grep.

To do it with just grep, you need non-standard extensions like here with GNU grep using PCRE (-P) with positive lookbehind (?<=..) and match only (-o):

grep -Po '(?<=miss rate ).*' yourfile

这篇关于如何仅使用grep/sed提取子字符串和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆