Saturday, April 9, 2022

[SOLVED] How to grep line which contains two commas

Issue

I have a file of IP and every line have two or three comma separated IP like -

ip x 171.48.179.64, 194.88.105.83, 10.121.15.191
ip x 122.176.17.76, 194.88.105.83, 10.121.15.191
ip x 223.179.196.169, 10.121.15.135
ip x 157.41.161.64, 10.121.15.135
ip x 49.14.160.119, 10.121.15.191
ip x 157.41.230.108, 10.121.15.191
ip x 101.208.189.88, 194.88.105.83, 10.121.15.191
ip x 180.215.137.150, 194.88.105.83, 10.121.15.191
ip x 157.41.161.64, 10.121.15.191
ip x 157.41.161.64, 10.121.15.191

So I want to grep the lines which contains two comma (three IPs) like -

ip x 171.48.179.64, 194.88.105.83, 10.121.15.191
ip x 122.176.17.76, 194.88.105.83, 10.121.15.191
ip x 101.208.189.88, 194.88.105.83, 10.121.15.191
ip x 180.215.137.150, 194.88.105.83, 10.121.15.191

I searched a lot but did't get any specific answer, please help me.


Solution

You can use awk:

awk -F, 'NF==3' file

-F, sets the delimiter to ,. NF is a special variable which contains the number of fields. If the condition NF==3 is met awk will print the current line.


With (e)grep it would be something like this:

grep -E '^([^,]+,){2}[^,]+$' file

I would personally use awk because it is much more readable.



Answered By - hek2mgl
Answer Checked By - Robin (WPSolving Admin)