Files with same name

69 Views Asked by At

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
4

There are 4 best solutions below

0
Lev Levitsky On

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.

0
Kent On

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
0
RARE Kpop Manifesto On
 {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
0
ufopilot On
$ 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