Phoebe
Phoebe

Reputation: 123

How to get the first number after a string in 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 :)

Upvotes: 4

Views: 1250

Answers (2)

Adam
Adam

Reputation: 36743

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.

Upvotes: 1

badjr
badjr

Reputation: 2296

A solution using grep:

cat file.txt | grep -A2 'Jim' | grep -Eo '[0-9]*'

Upvotes: 2

Related Questions