LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: Insert output of a commando into an array and compare the values (https://www.linuxquestions.org/questions/programming-9/bash-insert-output-of-a-commando-into-an-array-and-compare-the-values-717162/)

tengblad 04-06-2009 07:48 AM

Bash: Insert output of a commando into an array and compare the values
 
Hello all,
I'm still sort of a beginner at bash scripting and need help with the following.

I have a set of commands that will output a list of values. The exact values, and number thereof, is not set and can and will vary each time I run the command.

What I want to do is to insert the output of this commando into an array, and them compare how many instances of each digit is present. If one digit appears more times then rest I want to print text to standard output.

An example.

cat ./hba.txt | grep '.:.:.:.' | awk -F: '{print $1}' | cut -c4-5
returns the following list:
Quote:

0
0
2
2
0
0
[..]
3
3
1
1
3
3
1
1


What I want to do is count how many times 0 appears, how many times 1 appears and how many times 2 and so on. I then want to compare these values and if one of these numbers appear more than the rest, I want to echo something.

With sort | uniq -c I added on to the end of the first line I can see that 0 appears twelve times, 1 eight times, 2 twelve times and 3 eight times:
Quote:

12 0
8 1
12 2
8 3
So, what I really need help with is finding a way to compare them!

Thanks in advance.

grunt547 04-06-2009 11:28 PM

Well, you could pipe it through another sort:
Code:

sort | uniq -c | sort -rg
Then you'll get out a list in descending order by numerical value. If you wanted to limit your results, you could then pipe it through "head" or something.

jan61 04-07-2009 03:36 PM

Moin,

in summary: You want to write some text for the value with the highest number of occurences?

First I'd use one sed to prepare the file instead of 4 commands in a pipeline:
Code:

sed -n '/.:.:.:./{s/:.*//;s/^...\(..?\).*/\1/;p}' hba.txt
To get the maximum of occurences at the first line: The first sort in grunt547's command is not necessary. To add a comment on this line you can again use sed:
Code:

sed ... | uniq -c | sort -rg | sed '1s/$/ this is the maximum/'
Jan


All times are GMT -5. The time now is 04:45 AM.