Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first number after a string in bash

Tags:

linux

bash

For example, if I have those line in a file called input.txt

name: Tom

age: 12

name: Bob

age: 13

name: Jim

age: 14

name: Joe

age:15

I want the first number after Jim, which is 14. Thanks :)

like image 239
Phoebe Avatar asked Oct 29 '25 18:10

Phoebe


2 Answers

A solution using grep:

cat file.txt | grep -A2 'Jim' | grep -Eo '[0-9]*'
like image 181
badjr Avatar answered Nov 01 '25 12:11

badjr


There are multiple solutions to this, using tools including sed, awk, cut, etc. However I prefer 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.

  • -0777 is Perl Slurp mode used in combination with /m for multiline matching.

like image 30
Adam Avatar answered Nov 01 '25 13:11

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!