0

I am trying to look at a directory named Forever where it has sub-directories with Pure,Mineral which are filled with .csv files. I was able to see all the .csv files in the directory, but I am having hard time sorting them according to the length of filename.

As for current directory, I am at Forever. So I am looking at both sub-directories Pure and Mineral.

What I did was:

find -name ".*csv" | tr ' ' '_' | sort -n -r

This just sorts the file reverse alphabetically, which doesn't consider the length.(I had to truncate some name of the files as it had spaces between them.)

Rafael
  • 7,605
  • 13
  • 31
  • 46
colbyjackson
  • 175
  • 2
  • 10
  • 1
    Possible duplicate of [Sorting file names by length of the file name](https://stackoverflow.com/questions/9868408/sorting-file-names-by-length-of-the-file-name) – 273K Jan 27 '19 at 03:13
  • These questions might be similar (sorting based on filename length), but they're not the same; one accounts for subdirs while the other does not. – Rafael Jan 27 '19 at 04:19

1 Answers1

2

I think this answer is more helpful than the marked duplicate because it also accounts for sub-dirs (which the dupe didn't):

find . -name '*.csv' -exec bash -c 'echo -e $(wc -m <<< $(basename {}))\\t{}' \; | sort -nr | cut -f2

FWIW using fd -e csv -x ... was quite a bit faster for me (0.153s vs find's 2.084s)

even though basename removes the file ext, it doesn't matter since find ensures that all of them have it

Rafael
  • 7,605
  • 13
  • 31
  • 46