Reputation: 1170
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.
Upvotes: 2
Views: 5336
Reputation: 1
you can also use a loop
while read -r line
do
count=${line//[^,]};
if [ ${#count} == 2 ];
then
echo "${line}";
fi
done < your.file
Upvotes: 0
Reputation: 133428
In case you have other lines too which could have anything else from IPs then following may help you which will check number of fields as well as make sure 1st, 2nd and 3rd fields are having IPs nothing else.
awk -F, 'NF==3 && \
$1 ~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ && \
$2 ~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ && \
$3 ~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/' Input_file
Upvotes: 1
Reputation: 157947
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.
Upvotes: 7