Novice
Novice

Reputation: 1161

Bash Script to save grep -c results

I am new to programming altogether and am trying to write my first bash script.

I have a file called NUMBERS.txt that has various numbers in it, as such:

1000
1001
1001
1000
1002
1001
etc..

I would like to write a script to count the occurrence of each number, save it as a variable and print it into a new text file as such:

1001= 3
1000= 2
etc..

I am completely stuck.

Here's what I have so far:

 #!/bin/bash

for Count in `grep -c '1000' /NUMBERS.txt `
do
echo 'Count = '${Count}
done

for Count in `grep -c '1001' /NUMBERS.txt `
do
echo 'Count = '${Count}
done

Upvotes: 0

Views: 764

Answers (3)

CS Pei
CS Pei

Reputation: 11047

Now your file is already have one number on each line, it is simpler

 for i in `sort -u NUMBERS.txt ` ; do count=`grep -c "$i" NUMBERS.txt ` ; echo "$i=$count" ; done  > your_result.txt

or in a different format

for i in `sort -u NUMBERS.txt `
do
    count=`grep -c "$i" NUMBERS.txt `
    echo "$i=$count"
done  > your_result.txt

As asked by , the performance is not very good. here is a much better one

sort NUMBERS.txt | uniq -c | awk '{print $1,"=",$2}'

Basically you go through NUNMBERS.txt twice. The first pass, you get the unique numbers; The second pass you count the occurrence of each unique number.

Upvotes: 1

DCMaxxx
DCMaxxx

Reputation: 2574

I'm not the best at shell script, but here is a solution that works, using bash and grep -c :

#!/bin/bash

INPUT="./numbers.txt"
OUTPUT="./result.txt"

rm -f ${OUTPUT}

# you might want to change the values
for i in {1000..2000}; do
    for Count in `grep -c ${i} ${INPUT}`; do
    echo "${i} = ${Count}" >> ${OUTPUT}
    done
done

Upvotes: 1

Alexander Hanysz
Alexander Hanysz

Reputation: 801

Sort the file then count how many times each unique line occurs:

sort NUMBERS.txt | uniq -c

Upvotes: 4

Related Questions