sorting files on linux

1

I have multiple files in a directory they have numeric digits before their extensions. like below:

  • SHG_PS_RG_10.tif
  • ABC_MFCL_NHG_PS_RG_af_04.tif
  • SHG_PS_RG_af_01.tif
  • CBC_MFCL_NHG_PS_RG_af_03.tif

etc.. I want to sort them with the numeric (01,03,04 etc) like below:

  • SHG_PS_RG_af_01.tif
  • CBC_MFCL_NHG_PS_RG_af_03.tif
  • ABC_MFCL_NHG_PS_RG_af_04.tif
  • SHG_PS_RG_10.tif

How can I do this?

Jamal

Posted 2017-02-22T10:36:46.090

Reputation: 11

Answers

1

nifle@megamart ~/tmp
$ echo "SHG_PS_RG_10.tif
  ABC_MFCL_NHG_PS_RG_af_04.tif
  SHG_PS_RG_af_01.tif
  CBC_MFCL_NHG_PS_RG_af_03.tif" > foo.txt

nifle@megamart ~/tmp
$ awk -F "_" '{print $NF,$0}' foo.txt  | sort -n | cut -f2- -d' '

SHG_PS_RG_af_01.tif
CBC_MFCL_NHG_PS_RG_af_03.tif
ABC_MFCL_NHG_PS_RG_af_04.tif
SHG_PS_RG_10.tif

Explanation

  • -F "_" tells awk that we use '_' as a field separator
  • $NF is awk'ish for the last field 10.tif
  • $0 is awk'ish for the whole input SHG_PS_RG_af_01.tif
  • so this '{print $NF,$0}' prints 10.tif SHG_PS_RG_10.tif

    When we have 10.tif SHG_PS_RG_10.tif it's easy to do sort -n and then we use cut -f2- -d' ' to print out only the second column.

Nifle

Posted 2017-02-22T10:36:46.090

Reputation: 31 337

Thanks but i forgot to ask that i have spaces in the names of files like "SHG_PS RG_10.tif ". in this case what should i do ? how will we tell awk that in some files we have space and in other files we have underscore as field seperator. please propose a solution – Jamal – 2017-02-22T11:51:38.883

1I tried the command ls -1 af | tr -s ' ' '' | awk -F '' '{print $NF , $0}' | sort -n | cut -f2 -d' and it worked ! :) Thanks. – Jamal – 2017-02-22T12:10:59.460