1

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?

14
  • You can add another grep or sed to cut this info out. Commented Dec 25, 2013 at 8:57
  • @AndrewLogvinov I can do it by adding the following pipes to my command | cut -f2 -d'[' | cut -f1 -d']' but I want to know how to it with the same grep Commented Dec 25, 2013 at 9:01
  • I'm afraid you cannot do it using just one single grep. Commented Dec 25, 2013 at 9:05
  • Yes it can be done in a single grep using -P (PCRE) switch. I provided an answer below. Commented Dec 25, 2013 at 9:08
  • 1
    @anubhava thank you very much for your time and effort Commented Dec 25, 2013 at 9:37

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I m using a limited version of grep from busybox and it does not supported the -P option
@MOHAMED what about sed?match [12 and use sed to replace [.
0

Pipe it to sed and use a back reference:

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

2 Comments

You should now that grep can read files and cat is not needed.
@Jotne I do know that... I just took OP's partial solution and bolted on the extra part needed to do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.