Reputation: 44381
I need to order a list of files by file name. Currently I do the ordering like this:
» find . -name "*.fixtures.json" | sort
./my_registration/fixtures/0600-my_registration.fixtures.json
./soamgr/fixtures/0200-soamgr.fixtures.json
./soaprj/fixtures/0100-users.fixtures.json
./soaprj/fixtures/0110-permissions.fixtures.json
./soaprj/fixtures/0120-groups.fixtures.json
Which is ordering by full path (as expected).
In this case I would like to order just by file name (so that my number prefixes are the ones defining the ordering), but keeping the path information. This is the output I would need:
./soaprj/fixtures/0100-users.fixtures.json
./soaprj/fixtures/0110-permissions.fixtures.json
./soaprj/fixtures/0120-groups.fixtures.json
./soamgr/fixtures/0200-soamgr.fixtures.json
./my_registration/fixtures/0600-my_registration.fixtures.json
Is there an easy way to do this in bash, with standard unix tools?
Upvotes: 1
Views: 38
Reputation: 88644
Append this to your find to use a Schwartzian transform:
| awk -F/ '{print $NF "/" $0}' | sort -n | cut -d / -f 2-
Output:
./soaprj/fixtures/0100-users.fixtures.json ./soaprj/fixtures/0110-permissions.fixtures.json ./soaprj/fixtures/0120-groups.fixtures.json ./soamgr/fixtures/0200-soamgr.fixtures.json ./my_registration/fixtures/0600-my_registration.fixtures.json
awk:
-F
: sets the field separator
$NF
: number of fields in the current record / last column
$0
: whole line of arguments
Upvotes: 3
Reputation: 67507
If the depth is not fixed you use something like this
$ sed 's_.*/_& _' files | sort -k2n | sed 's_/ _/_'
./soaprj/fixtures/0100-users.fixtures.json
./soaprj/fixtures/0110-permissions.fixtures.json
./a/b/c/d/0115-dummy.json
./soaprj/fixtures/0120-groups.fixtures.json
./soamgr/fixtures/0200-soamgr.fixtures.json
./my_registration/fixtures/0600-my_registration.fixtures.json
I added a dummy record to verify sorting. Assumes no spaces in file names or paths.
Upvotes: 1
Reputation: 19278
If directory depth is the same for all the files (3 in your example) the following will work:
find . -name "*.fixtures.json" | sort -t/ -k 4n
Upvotes: 1