Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uniq on array, not displaying correctly

I am new to bash programming and I am struggling with arrays and how to operate with them. SCENARIO:

I have a variable called x which is composed of a group of IP's. This is the output when I echo $x from my script

182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 201.21.24.22 201.21.24.22 201.21.24.22
44.21.25.31 44.21.25.31 44.21.25.31 44.21.25.31
 

Then, I would like to know how many times each IP is repeated. The desired output would be:

15 182.100.67.59
4 44.21.25.31
3 201.21.24.22

I have tried the following

(IFS=" "; sort <<< "$x" ) | uniq -c

Output Note the first 1 on the output.

**1** 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 182.100.67.59 201.21.24.22 201.21.24.22 201.21.24.22 44.21.25.31 44.21.25.31 44.21.25.31 44.21.25.31 

I am not seeing this, It should be pretty simple but I can't find the solution :( Thanks! And very great community!

like image 733
Learner33 Avatar asked Apr 15 '26 09:04

Learner33


1 Answers

Method 1:
Use tr to replace spaces with newlines, followed by sort | uniq -c:

tr ' ' '\n' <<<"$x" | sort | uniq -c

Method 2:
Use echo with xargs -n1 to write the IPs one per line, followed by sort | uniq -c. Note that xargs is slower than tr here, plus may have potential side effects, such as quote removal:

echo "$x" | xargs -n1 | sort | uniq -c
like image 54
2 revsTimur Shtatland Avatar answered Apr 16 '26 23:04

2 revsTimur Shtatland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!