Luca
Luca

Reputation: 41

grep variable string in file

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.

Upvotes: 1

Views: 678

Answers (2)

Jahid
Jahid

Reputation: 22448

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]\+'

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74705

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.

Upvotes: 8

Related Questions