有下一个测试文件
some text http://example.com/redirect?http://some/test.html #not wanted
some text http://example.com/notete.html #not wanted
some text http://example.com/redirect?http://some/anyttany.html #wanted
some text http://example.com/http.html #wanted
some text http://example.com/tt.html #wanted
some text http://example.com/somett.html #wanted
some text http://example.com/somettsome.html #wanted
some text /example.com/somettsome.html #wanted (path only)
下一个:
grep -P 'http://\S*tt(?!p:)' file
打印
some text http://example.com/redirect?http://some/anyttany.html #wanted
some text http://example.com/http.html #wanted
some text http://example.com/tt.html #wanted
some text http://example.com/somett.html #wanted
some text http://example.com/somettsome.html #wanted
意思
http:// 'http://'
----------------------------------------------------------------------
\S* non-whitespace (all but \n, \r, \t, \f,
and " ") (0 or more times (matching the
most amount possible))
----------------------------------------------------------------------
tt 'tt'
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
p: 'p:'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
和
grep -cP 'http://\S*tt(?!p:)' file
将计算匹配的行数
如果开头的http:// 是可选的,
grep -P '(<=http://)?\S*tt(?!p:)' file
将执行相同的工作并针对相同的输入打印
some text http://example.com/redirect?http://some/anyttany.html #wanted
some text http://example.com/http.html #wanted
some text http://example.com/tt.html #wanted
some text http://example.com/somett.html #wanted
some text http://example.com/somettsome.html #wanted
some text /example.com/somettsome.html #wanted (path only)
用于捕获 URL(和路径)
grep -oP '.*?\K(http:/)?/\S*tt(?!p:)\S*' file
打印
http://example.com/redirect?http://some/anyttany.html
http://example.com/http.html
http://example.com/tt.html
http://example.com/somett.html
http://example.com/somettsome.html
/example.com/somettsome.html
仅捕获http://
grep -oP '.*?\Khttp://\S*tt(?!p:)\S*' file
http://example.com/redirect?http://some/anyttany.html
http://example.com/http.html
http://example.com/tt.html
http://example.com/somett.html
http://example.com/somettsome.html