0

How can I sort filenames like this

B-100.txt
B-11.txt
A-03.txt
A-01.txt
C-110.txt
C-10.txt

into this?

B-11.txt
B-100.txt
A-01.txt
A-03.txt
C-10.txt
C-110.txt

I'd like to leave the prefix order --B, A, and then C, not ABC-- as is but sort the numbers at the end numerically not alphabetically. The numbers go like

01, 02, ....10, 11, ....100, 101, ...

There's always one hyphen in each filename and it delimits the prefix part and the number part.

I'd like to sort the filenames of files that I export from some software and the software automatically adds this kind of peculiar serial numbers at the end so I'm in trouble generating a sorted list of those filenames. I can't rename those files before sorting.

  • 2
    Does $ for prefix in B A C; do ls -1 ${prefix}* | sort -V ; done do what you want for your actual use-case? It seems to work for the sample set you have provided. – DopeGhoti Dec 7 '16 at 20:47
  • @DopeGhoti Sorry, I should've clarified more: the filename list's going to be updated frequently, so I'll never know what the prefix string is going to be. It might be sea, mountain, park or August, March4, June1 or whatever, but there's only one hyphen in each filename and it delimits the prefix and the number so I want to use it, but is it possible at all? – stacko Dec 7 '16 at 21:10
  • 1
    If you don't know what the prefixes are going to be, it will be hard to put them in a non-lexical order, but ls * | sort -V will keep prefix-grouping. Also, the -1 in my earlier comment is not needed as a non-interactive ls has the output -1 implies in an interactive terminal. – DopeGhoti Dec 7 '16 at 21:16
  • how do you receive the list of files? Are they files in a directory, or entries in a text file? what's the desired output: an array? printed to the screen? renamed with nicer serial numbers? per DopeGhoti's last point, if you don't know the prefix, how should it be sorted? – Jeff Schaller Dec 8 '16 at 2:43
0
(
  SECTION=""
  OLDPREFIX="-invalid"
  while read LINE
  do
    PREFIX="${LINE/-*/}"
    if [ "$PREFIX" == "$OLDPREFIX" ]
    then
      SECTION="$SECTION"$'\n'"$LINE"
    else
      echo "$SECTION" | tail -n +2 | sort -V
      SECTION=$'\n'"$LINE"
      OLDPREFIX="$PREFIX"
    fi
  done
  echo "$SECTION" | tail -n +2 | sort -V
) <<'EOF'
B-100.txt
B-11.txt
A-03.txt
A-01.txt
C-110.txt
C-10.txt
EOF
0

i am using red-hat linux.

$ awk -F- '!A[$1]++{print $1}' input.txt | while read px; do grep "$px" input.txt | sort -n -t- -k2; done
B-11.txt
B-100.txt
A-01.txt
A-03.txt
C-10.txt
C-110.txt

$ cat input.txt
B-100.txt
B-11.txt
A-03.txt
A-01.txt
C-110.txt
C-10.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.