2

i am using this script that read the file and show me the unique Name from the file and also show me how many times this Name exist(number of count) in the file

john
john
William
wad
William
john
wad
john
wad
john
William
john
wad
john
wad
wad
john
john

cat student.txt | awk '{print $1}' | sort | uniq -c | sort -nr | head -n 10

its output:

9 John
6 Wad
3 William

i want to change this format, i want first Name then Number of count, how can i do this with above script

 John 9
 Wad 6
 William 3
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Kashif
  • 27
  • 6

3 Answers3

1

Append to your command:

| awk '{print $2,$1}'
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

Your pipe is way too long. Awk has associative arrays for this purpose:

$ awk '{++count[$1]} END {for (name in count) print name, count[name]}' student.txt |
sort -nr -k 2
john 9
wad 6
William 3
Jens
  • 69,818
  • 15
  • 125
  • 179
0

Using Perl: The command to count the number of occurrences of each input line, sort the output from most to least frequent, and print each line followed by the count (tab-delimited):

echo William Wad John William John William William | xargs -n1 | \
    sort | uniq -c | sort -nr | \
    perl -lane 'print join "\t", reverse @F'

Prints:

William 4
John    2
Wad     1

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.

print join "\t", reverse @F : read it right to left: reverse the array @F (the input fields), join the elements on a tab into a string, and print that string.

To replace tab with blank, use:
print join " ", reverse @F

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47