grep的最短匹配

給定字符串"fn=doAction&a=1&b=2",提取出fn=doAction&。bash

echo "fn=doAction&a=1&b=2" | grep -o "fn=.*&"
# fn=doAction&a=1&

輸出‘fn=doAction&a=1&’,因爲grep的匹配是貪婪的,匹配了最長的&。code

改成字符串

echo "fn=doAction&a=1&b=2" | grep -o -P "fn=.*?&"
# fn=doAction&

-P參數使用perl模式正則,*後面加個?使用non-greedy模式,搞定。io

https://stackoverflow.com/questions/3027518/how-to-do-a-non-greedy-match-in-grep#3027524class

相關文章
相關標籤/搜索