LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Help for bash script (http://www.linuxquestions.org/questions/linux-general-1/help-for-bash-script-4175443486/)

circus78 12-30-2012 11:21 AM

Help for bash script
 
Hi,
I've a very long text file with this kind of content:

Quote:

aaaaaaaaa
bbbbbbbbb
ccccccccc
bbbbbbbbb
bbbbbbbbb
aaaaaaaaa
aaaaaaaaa
aaaaaaaaa
..
..
Obviously this can be very easily sorted.
My goal is to obtain a "count" for every code.
For example, if "aaaaaaaaa" appears 576 time, "bbbbbbbbb" 78, "ccccccccc" 921 and so on:

Quote:

aaaaaaaaa,576
bbbbbbbbb,78
ccccccccc,921
...
...
How can I do this?
Thankyou!

Habitual 12-30-2012 11:53 AM

Code:

man uniq

User\ Name=`echo $USER` 12-31-2012 03:57 PM

Try this:
Code:

for i in `cat test.txt | sort -u`; do                                           
  count=`grep ${i} test.txt | wc -l`;                                           
  echo "${i},${count}"                                                           
done

Just replace test.txt with the name of your text file. This will give you the exact output you put in your OP.

Hope this helps. :)

konsolebox 01-01-2013 03:29 AM

If you use Bash 4.0+, it's actually just simple:
Code:

#!/bin/bash

declare -A INSTANCES

while read LINE; do
        (( INSTANCES[$LINE]++ ))
done

for KEY in "${!INSTANCES[@]}"; do
        echo "$KEY,${INSTANCES[$KEY]}"
done

Code:

# bash script.sh < input_file

kooru 01-02-2013 02:39 AM

Code:

sort yourfile | uniq -c


All times are GMT -5. The time now is 11:01 PM.