1836581 Members
1544 Online
110102 Solutions
New Discussion

ShellScript help pl

 
SOLVED
Go to solution
Ashwin_4
Frequent Advisor

ShellScript help pl

Hi Masters,
I've the following file,
1 a
1 a
1 a
1 b
1 b

I want the following output:
1 a 3
1 b 2

Pl help
6 REPLIES 6
Steve Steel
Honored Contributor

Re: ShellScript help pl

Hi


This script with filename as parameter

file=$1
sort -u $file|while read line
do
echo "$line"" "$(grep "$line" $file|wc -l)
done

For scripting see

http://www.shelldorado.com/


Steve Steel
If you want truly to understand something, try to change it. (Kurt Lewin)
Stuart Whitby
Trusted Contributor
Solution

Re: ShellScript help pl

Steve's answer's perfectly correct as long as that's the exact format of your file. If you can have a file which has:

1 a
1 a
1 b
1 c
1 a
1 a
1 b

and *still* want

1 a 4
1 b 2
1 c 1

then use

cat | sort -n | uniq -c | awk '{ print $2 " " $3 " " $1 }'
A sysadmin should never cross his fingers in the hope commands will work. Makes for a lot of mistakes while typing.
H.Merijn Brand (procura
Honored Contributor

Re: ShellScript help pl

or

# perl -ne'$x{$_}++}END{for(sort keys%x){s/$/ $x{$_}/;print}' file

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Hein van den Heuvel
Honored Contributor

Re: ShellScript help pl

and finally, in case you need some further data massaging along the lines (sic), here is an awk solution for a sorted file:

awk 'BEGIN {getline x}{i++;if (x!=$0) {print x,i;i=0;x=$0}} END {print x, ++i}' sorted_input

BEGIN - preset last seen record value
loop - always count. if new value not equal to old then: print value &count and reset value & count
END - print final value & count


fwiw,

Hein.

Re: ShellScript help pl

sort filename | uniq -c | sed -e 's:\([0-9][0-9]*\)\([ ][ ]*\)\(.*\)$:\3\2\1:'
Singaram
Advisor

Re: ShellScript help pl

Hi Stuart

Steve's Solution works perfectly in all cases. It works in your file as well ashwin's file

Singaram