MOHAMED
MOHAMED

Reputation: 43518

How to extract a number from a string using grep and regex

I make a cat of a file and apply on it a grep with a regular expression like this

cat /tmp/tmp_file | grep "toto.titi\[[0-9]\+\].tata=55"

the command display the following output

toto.titi[12].tata=55

is it possible to modify my grep command in order to extract the number 12 as displayed output of the command?

Upvotes: 1

Views: 6920

Answers (3)

anubhava
anubhava

Reputation: 784898

You can grab this in pure BASH using its regex capabilities:

s='toto.titi[12].tata=55'
[[ "$s" =~ ^toto.titi\[([0-9]+)\]\.tata=[0-9]+$ ]] && echo "${BASH_REMATCH[1]}"
12

You can also use sed:

sed 's/toto.titi\[\([0-9]*\)\].tata=55/\1/' <<< "$s"
12

OR using awk:

awk -F '[\\[\\]]' '{print $2}' <<<"$s"
12

Upvotes: 2

oyss
oyss

Reputation: 692

use lookahead

echo toto.titi[12].tata=55|grep -oP '(?<=\[)\d+'
12

without perl regex,use sed to replace "["

echo toto.titi[12].tata=55|grep -o "\[[0-9]\+"|sed 's/\[//g'
12

Upvotes: 1

Bohemian
Bohemian

Reputation: 424983

Pipe it to sed and use a back reference:

cat /tmp/tmp_file | grep "toto.titi\[[0-9]\+\].tata=55" | sed 's/.*\[(\d*)\].*/\1/'

Upvotes: 0

Related Questions