Using Grep Regex to find certain IP addresses in a txt

I am trying to figure out how to use the grep regex command to filter out IPs.
My first problem is to tell how many IPs only have one digit in the first octet.
And the second is to find all IPs with the number 244 in the first octet.

Ive tried grep -o -n '\b[0-9].' file.txt

but this just finds any 1 digit, then I also tried setting up each place [0-9]{1,3} but I still dont get the righ output.

file format:
192.168.1.1
54.28.144.21
1.58.65.44
244.98.55.11

output 1:
1.58.65.44
output 2:
244.98.55.11

Any help would be much appreciated

welcome to the community, @Tiberious01
It always helps others if the OP provides a small representative input file AND the desired output file based on the sample input.

You are on the right track with

[0-9]{1,3}

A valid IP address is
1-3 digits, followed by a period
1-3 digits, followed by a period
1-3 digits, followed by a period
1-3 digits

Remember, though that a period is a regex expression for a single character, so you need to escape it:

[0-9]{1,3}\.

So, I'd say make a regex that matches the IP addresses. Remove the -o and the \b. See what kind of matches you get, then adjust your regex and arguments as you go.

Use ERE (grep -E or egrep).
If the IPs are at the beginning of the line then it is
egrep '^[0-9][.]'
The dot has a special meaning in a RE: "any character". A literal dot must be escaped \. or put in a character set [.]
To match a IP in the middle of tbe line, it is more complicated:
egrep -o '\<[0-9]([.][0-9]{1,3}){3}\>'
The ( ) group consists of a dot followed by 1-3 digits, and the group is repeated 3 times.
The \< and \> are word boundaries; \b might work as well.

Given that all the input data seem to be valid IP addresses (only containing digits and dots), and the requirement only deals with the first octet, there seems to be no need to verify all the octets as being numeric, or of 1-3 digits.

Note the first requirement states only "how many". It does not ask for details. Trick question?

#.. How many IPs only have one digit in the first octet.
$ grep '^.[.]' ipFile.txt | wc -l
1
$ awk '/^.[.]/ { ++N; } END { print 0 + N; }' ipFile.txt
1
#.. Find all IPs with the number 244 in the first octet.
$ grep '^244[.]' ipFile.txt
244.98.55.11
$ awk '/^244[.]/' ipFile.txt
244.98.55.11

note that [0-9]{1,3} is a necessary but not a sufficient condition for a valid octet, since then e.g. 314 would be found. For further information see e.g. regex - Validating IPv4 addresses with regexp - Stack Overflow.

1 Like