开发者

How to grab last character in a regex with 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 开发者_如何学Gothe non-greedy operator but it does not seem to work :

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

It return nothing

The expected result is titi.


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.)


Basically, what you are doing is just getting the first character of the last field. The more approachable method than regex is using a tool that can split strings into fields and doing "substring-ing".

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


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


EDIT: I just saw a better answer to this post, but posting this anyway, as it might be helpful if you want to do something more complex, like substituting things.

Another way to do this as is to use the sedcommand and let it substitute (with the s command first in the regex) everything except that which you want (which is collected into the variable \1 by the parentheses:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜