System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

script to search more than 2 instances of same number in text file?

SOLVED
Go to solution
Sammy_2
Super Advisor

script to search more than 2 instances of same number in text file?

(/bin/ksh or /bin/bash) shell
How to write script to print ONLY numbers which appear more than 2 times in a file below (numbers.txt).

So, output from from running thes scirpt (script.sh) after processing the txt file below should only show something like:
=================
#./script.sh

6 appears 3 times
1 appears 1 times

===================

numbers.txt
===========
12
12
111
111
6
6
6
1
22
22
good judgement comes from experience and experience comes from bad judgement.
4 REPLIES
James R. Ferguson
Acclaimed Contributor
Solution

Re: script to search more than 2 instances of same number in text file?

Hi:

# uniq -c file

...which for your input yields:

2 12
2 111
3 6
1 1
2 22

Regards!

...JRF...
Patrick Wallek
Honored Contributor

Re: script to search more than 2 instances of same number in text file?

If your file is not already sorted, you could do:

# sort -n numbers.txt | uniq -c
Sammy_2
Super Advisor

Re: script to search more than 2 instances of same number in text file?

JRF and Pat,
Thanks. It was simpler than I thougt. That is what I needed.
Appreciate it.
Sam
good judgement comes from experience and experience comes from bad judgement.
Hein van den Heuvel
Honored Contributor

Re: script to search more than 2 instances of same number in text file?

Sammy, if you ever need more than counting. Maybe some pretty printing or further filtering the you may want to build on top of a perl/awk solution. Something like:

$ perl -ne 'chomp; $x{$_}++} { for (keys %x) {printf qq(%3d appears %3d times\n),$_,$x{$_}}' number.txt

22 appears 2 times
6 appears 3 times
1 appears 1 times
111 appears 2 times
12 appears 2 times

chomp; # take away new-line
$x{$_}++ # increment associative array element identified by line $_
} { # close input loop, open END block.
for (keys %x) { # what he said
printf qq(%3d appears %3d times\n) # formatted print
,$_,$x{$_} # variables are key and value for key
}' # close keys block, end program
number.txt # input stream.

hth,
Hein.