Home > OS >  sort by name on bash same as graphical on windows
sort by name on bash same as graphical on windows

Time:08-09

I have this folder in windows

text

if I do a simple ls , find, either in bash (cygwin) or msdos, it shows me like this.

$ ls -1
su-01-01.jpg
su-01-02-03.jpg
su-01-12-13.jpg
su-01-14.jpg
su-01-15.jpg
su-01-16.jpg
su-01-18.jpg
su-01-19.jpg
su-01-20.jpg
su-01-21.jpg
su-01-31.jpg
su-01-34.jpg
su-01-35.jpg
su-01-38.jpg
su-01-39.jpg
su-01-42-43.jpg
su-01-44.jpg
su-01-45.jpg
su-01-47.jpg
su-01-48.jpg
su01-00.jpg
su01-04.jpg
su01-05.jpg
su01-06.jpg
su01-07.jpg
su01-08.jpg

I have tried ordering and it does not take into account 0 00 1

$ ls -1 |sort -V
su01-00.jpg
su01-04.jpg
su01-05.jpg
su01-06.jpg
su01-07.jpg
su01-08.jpg
su01-09.jpg
su01-10.jpg
su01-11.jpg
su01-22-23.jpg
su01-24.jpg
su01-25.jpg
su01-26.jpg
su01-27.jpg
su01-28-29.jpg
su01-30.jpg
su01-32.jpg
su01-33.jpg
su01-40-41.jpg
su-01-01.jpg
su-01-02-03.jpg
su-01-12-13.jpg
su-01-14.jpg
su-01-15.jpg

but how do I make it ignore the (-)?

thank you very much for your help

CodePudding user response:

find doesn't guaranty alphabetical ordering; ls and sort do, but the char - value is 45 while the 0 char value is 48, so su- will come ahead of the su0 in an alphabetical sorting.

While a printf '%s\n' su* | LANG=en_US.utf8 sort -n seems to display the files the way you want, the best thing to do for making your life easier would be to rename some of the files:

#!/bin/bash

for f in su0*
do
    mv "$f" "su-0${f#su0}"
done

Update

renaming the files to 001.jpg 002.jpg ...

#!/bin/bash
shopt -s nullglob

n=1
while IFS='' read -r file
do
    printf -v newname 'd.%s' "$((n  ))" "${file##*.}"
    printf '%q %q %q\n' mv "$file" "$newname"
done < <(
    printf '%s\n' su* |
    sed -nE 's,su-?([^/]*)$,\1/&,p' |
    LANG=C sort -nt '-' |
    sed 's,[^/]*/,,'
)

CodePudding user response:

The simplest way to control the sort order in Bash, both for ls and sort, so to set your LANG variable to the locale you want.

In your .bashrc or .profile, add

export LANG=en_US.utf8

and then

ls -1

or

ls -1 | sort

will output the order you're looking for.

If you want to test with different locales and see their effect, your can set LANG one command at a time. For example, compare the output of these commands:

LANG=en_US.utf8 ls -1  # what you're looking for
LANG=C ls -1           # "ASCIIbetic" order
LANG=fr_FR.utf8 ls -1  # would consider é as between e and f
  • Related