Home > Blockchain >  Files with same name
Files with same name

Time:06-24

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related