0

I have a file containing pathnames from two directories. I want to sort them by filename disregarding parent directories.

Text is as so:

/mnt/samsung/a/b/c
/mnt/samsung/d/e/f
...
/mnt/wd/a/b/c
/mnt/wd/d/e/f

I want to sort as

/mnt/samsung/a/b/c
/mnt/wd/a/b/c
/mnt/samsung/d/e/f
/mnt/wd/d/e/f

I'm trying with this :

 sort -t / -k3  

And it's not working.

I've tried also :

  sort -t "/" -k3 
  sort -t "/" -k2 
  sort -t / -k2

None of them working.

What will give what I want?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Stephen Boston
  • 2,178
  • 4
  • 32
  • 55
  • do you mean you want to sort on 3rd sub path ? or whatever subpaths that has only one char ? – francois P Nov 22 '19 at 20:12
  • 2
    The leading / means that a is the 4th field, not the 3rd – steeldriver Nov 22 '19 at 20:14
  • We need a bigger example. Can you add /mnt/wd/z/d to the input and output lists? This will give us some indication about filenames with differing number of components. Adding /mnt/wd/z/a/d and /mnt/wd/z/e/d as well would help us see what you mean by parent directories. – icarus Nov 22 '19 at 21:29

1 Answers1

2
$ sort -t '/' -k 6 file
/mnt/samsung/a/b/c
/mnt/wd/a/b/c
/mnt/samsung/d/e/f
/mnt/wd/d/e/f

For the given paths, the filename at the end of the path is the 6th /-delimited field on each line (the first field is zero-length).

Using --debug with GNU sort, it would output

$ sort --debug -t '/' -k 6 file
sort: text ordering performed using simple byte comparison
/mnt/samsung/a/b/c
                 _
__________________
/mnt/wd/a/b/c
            _
_____________
/mnt/samsung/d/e/f
                 _
__________________
/mnt/wd/d/e/f
            _
_____________

... showing that it is using the final path component as the sorting key.

Also possibly related (depending on what the actual task is):

Kusalananda
  • 333,661