How to capture the last character in a regex using grep

I am trying to capture the last space and what follows it line by line using grep.

This will capture my first space:

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

In Java, I would use a non-greasy operator, but it does not work:

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

He does not return anything

Expected Result titi.

+5
source share
3 answers

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

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

(If you want to use grepto use extended regular expressions, use egrepor grep -E.)

+6
source

: , , , - , , .

: sed ( s ) , , ( \1 :

echo "toto tata titi" | sed -r "s/.*( .*?)$/\1/"
+1

, , , . , , , "".

$ echo "toto tata titi" | awk '{print substr($NF,0,1)}'
t


$ echo "toto tata titi" | ruby -ane 'puts $F[-1][0]'
t
+1

All Articles