user823148
user823148

Reputation: 147

Linux grep pipe

I have a input.txt file containing a list of number:

1719
194
1719
1719
194
1135
194

I want to create a output.txt using a grep pipe in order to sort them in ascending order of the number of appearance, namely:

194: 3 times
1719: 2 times
1135: 1 time.

Any suggestions?

Upvotes: 0

Views: 525

Answers (4)

glenn jackman
glenn jackman

Reputation: 247162

awk '
    {count[$0]++} 
    END {for (n in count) {print n ": " count[n] " times"}}
' file |
sort -nr -k2

Upvotes: 2

miku
miku

Reputation: 188164

Assuming the numbers are in 6910460.txt without empty lines:

$ cat 6910460.txt | sort | uniq -c | sort -nr
3  194
2 1719
1 1135

Or if you need the text "times" as well, you can append an awk command:

$ cat 6910460.txt | sort | uniq -c | sort -nr | \
    awk 'BEGIN {FS=OFS=" "} \
        {temp=$2; $2=$1; $1=temp} {printf "%4i %4i time(s)\n", $1, $2}'

Which would print:

 194    3 time(s)
1719    2 time(s)
1135    1 time(s)

Upvotes: 3

iisulop
iisulop

Reputation: 46

I haven't got Linux at hand at the moment, but would something like this work:

cat input.txt | sort | uniq -c | sort -g

Upvotes: 0

user unknown
user unknown

Reputation: 36259

echo "1719
194
1719
1719
194
1135
194" | sort -n | uniq -c 
      3 194
      1 1135
      3 1719

Is this sufficient, or can you switch the values yourself?

Upvotes: 0

Related Questions