[英]How to get the first number after a string in bash
For example, if I have those line in a file called input.txt 例如,如果我在名为input.txt的文件中有这些行
name: Tom 姓名:汤姆
age: 12 年龄:12岁
name: Bob 姓名:鲍勃
age: 13 年龄:13岁
name: Jim 姓名:吉姆
age: 14 年龄:14岁
name: Joe 姓名:乔
age:15 年龄:15
I want the first number after Jim, which is 14. Thanks :) 我想要吉姆之后的第一个号码,这是14.谢谢:)
There are multiple solutions to this, using tools including sed
, awk
, cut
, etc. However I prefer perl
. 有多种解决方案,使用
sed
, awk
, cut
等工具。但我更喜欢perl
。
perl -0777 -nle 'print "$1\n" if /^name:\s*Jim\s*\nage:\s*([\d+.]+)/gm' file.txt
Explanation: 说明:
([\\d.]+)
matches any number after the age: on the next line after Jim. ([\\d.]+)
匹配年龄后的任何数字:在Jim之后的下一行。
-0777 is Perl Slurp mode used in combination with /m for multiline matching. -0777是与/ m结合使用的Perl Slurp模式,用于多行匹配。
使用grep
的解决方案:
cat file.txt | grep -A2 'Jim' | grep -Eo '[0-9]*'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.