Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab last character in a regex with grep

Tags:

regex

grep

I'm trying to grab the last space and what follows it on a line using grep.

This grab me the first space :

echo "toto tata titi" | grep -o " .*$"

In Java I would have used the non-greedy operator but it does not seem to work :

echo "toto tata titi" | grep -o " .*?$"

It return nothing

The expected result is titi.

like image 662
JPB Avatar asked Feb 16 '11 13:02

JPB


1 Answers

Replace . with [^ ], which matches everything but space. Then it can be greedy.

echo "toto tata titi" | grep -o " [^ ]*$"

(If you want grep to use extended regexes, either use egrep or grep -E.)

like image 182
Tim Avatar answered Sep 29 '22 18:09

Tim