0

I have used find and saved the result to file.txt file. Now I want to check files with same name sorted highest count first. e.g.:

/Volumes/1 drive/foo
/Volumes/1 drive/bar
/Volumes/1 drive/foo2
/Volumes/2 drive/foo
/Volumes/2 drive/bar2
/Volumes/3 drive/1/foo
/Volumes/3 drive/2/bar

I am running this command:

cat file.txt | awk -F '/' '{print $NR}' | uniq -c | sort

But awk output doesn't work correctly, it prints only first line:

Volumes
1 drive
foo

EDIT: The output should be:

3 foo
2 bar
1 foo2
1 bar2
user1869474
  • 57
  • 1
  • 1
  • 6

4 Answers4

2

If you are trying to delete the paths and only keep the part after the last slash, you can do it with sed like this: sed 's|.*/||'.

Note that you need a sorted column for uniq -c to work. So then if you want its output sorted as well, you need two sort calls:

> sed 's|.*/||' file.txt | sort | uniq -c | sort -rn
      3 foo
      2 bar
      1 foo2
      1 bar2

If you want to use awk, then you probably need $NF and not $NR:

awk -F '/' '{print $NF}' file.txt | sort | uniq -c | sort -rn

This use of awk is shown in this answer.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
1

Alternatively, you can try this awk one-liner:

$ awk -F'/' '{a[$NF]++} END{for (x in a)print a[x],x}' file.txt|sort -nr
3 foo
2 bar
1 foo2
1 bar2
Kent
  • 189,393
  • 32
  • 233
  • 301
0
 {m,n,g}awk '
 { __[$!++NF]++ } END { ___=_+=_=length(FS)
 
    PROCINFO["sorted_in"] = "@val_num_desc"
                   
    for (_ in __) {
         printf("%\047*.f %s\n",___,__[_],_) } }' FS='^.+[/]' OFS= \
                                           \
  | gsort -nr  # pipe over to sort for any non-gnu awk

       3 foo
       2 bar
       1 foo2
       1 bar2
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11
0
$ xargs -I "{}" basename "{}" <file|sort|uniq -c
      2 bar
      1 bar2
      3 foo
      1 foo2

$ xargs -I "{}" basename "{}" <file|sort|uniq -c|sed 's/^ *//'|sort -nr
3 foo
2 bar
1 foo2
1 bar2

Using find as input

find /your/path -type f -print0|xargs -0 basename -a|sort|uniq -c|sed 's/^ *//'|sort -nr
ufopilot
  • 3,269
  • 2
  • 10
  • 12