ilium007
ilium007

Reputation: 589

Sort a list of files based on numeric value in name

I have this list of files and I want to sort them and increment their names by an integer value, my code works fine until the list hits 10. The linux 'sort' command then interprets the first '1' in '10' and thinks it is a smaller number than 9. Is there any way to make this work ?

This is the code I have written to loop over a folder and increment file names:

#!/bin/bash

#set -x
ROOT=~/testing/
FILE_COUNT=$(ls -1 $ROOT | wc -l | awk '{print $1}')
COUNT=5

if [[ ${FILE_COUNT} -eq $COUNT ]]; then
    echo $COUNT backup files are there

    FILE_LIST=$(ls -1 $ROOT | sort -n -r)

    for file in $FILE_LIST; do
        echo $file
        file_new=`basename $file .zip`
        if [[ -e $ROOT$file ]]; then
            #mv $ROOT$file $ROOT${file_new%?}$COUNT.zip
            FILENUM=${file_new:${#file_new}-1}
            #echo "This is file # $FILENUM" next one is $(( FILENUM + 1 ))
            echo mv $ROOT$file $ROOT${file_new%?}$(( FILENUM + 1 )).zip
            mv $ROOT$file $ROOT${file_new%?}$(( FILENUM + 1 )).zip
        fi
        ((COUNT--))
    done
else
    echo Not $COUNT files, there are $FILE_COUNT
    COUNT=$FILE_COUNT
fi

And these are the results of the sort line:

macbookair:~ ilium007$ ls -l testing/ | sort -n -r -t "_"
total 40
-rw-r--r--  1 ilium007  staff  15 16 Nov 21:24 backup_9.zip
-rw-r--r--  1 ilium007  staff  15 16 Nov 21:24 backup_8.zip
-rw-r--r--  1 ilium007  staff  15 16 Nov 21:24 backup_7.zip
-rw-r--r--  1 ilium007  staff  15 16 Nov 21:24 backup_6.zip
-rw-r--r--  1 ilium007  staff  15 16 Nov 21:24 backup_10.zip

How do I create this list of files:

backup_10.zip
backup_9.zip
backup_8.zip
backup_7.zip
backup_6.zip

Any help appreciated.

Upvotes: 0

Views: 964

Answers (2)

ilium007
ilium007

Reputation: 589

This code ended up working:

#!/bin/bash

set -x
ROOT=~/testing/
FILE_COUNT=$(ls -1 $ROOT | wc -l | awk '{print $1}')
COUNT=5
FILENAME=("backup_19.zip"
"backup_2.zip
"backup_29.zip
"backup_38.zip")
for i in ${FILENAME[@]}; do
BASE_FILE_NAME=`basename $i .zip`
FILENUM=${BASE_FILE_NAME##*_}
NEW_FILE_NUM=$(( FILENUM + 1 ))
NEW_FILE_SUFFIX=$(( FILENUM + 1 )).zip
TEST=${BASE_FILE_NAME%%_*}_${NEW_FILE_SUFFIX}
done
exit

Upvotes: 0

dogbane
dogbane

Reputation: 274542

You need to specify the key to sort on, in this case -k2:

ls | sort -n -r -t "_" -k2

Upvotes: 1

Related Questions