grep variable string in file

故事扮演 提交于 2019-12-24 14:59:05

问题


I must find in a file this string:

200 https://www.example.example

The value 200 is randomic, I must find every HTTP return code (ex 200, 301, 404 etc...etc)

How can I grep only this string with return code variable (I don't want specify every return code in grep command)?

cat file.txt | grep "*** http*" 

But it doesn't work.


回答1:


So you want to match any line starting with a three digit number, followed by "http"?

grep -E '^[0-9]{3} http' file.txt

More accurate as suggested by fedorqui (thanks) would be this:

grep -E '^[1-5][0-9]{2} http' file.txt

This matches numbers in the range 100-599, which is closer to the range of HTTP status codes.




回答2:


First, there's no need for cat with grep. It can take a file argument itself.

You can do this:

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt

This will get you every line that matches with your criteria.

If you want only the return codes, you can run another grep or use other commands, for example with cut:

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt | cut -d ' ' -f1

and with grep,

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt | grep -o '^[0-9]\+'


来源:https://stackoverflow.com/questions/37001508/grep-variable-string-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!