1

I have folders I upload files to, with 1,000-20,000 files of different kinds (pdf, jpg, wmv...etc) with different file names and lengths with spaces in the names, etc.

I am trying make a script to rename them on a regular basis, but I want them sorted by "oldest date first", and the new name will be in the format of YYYT000001.xxxx ... YYYY036242.xxxx (where YYYY is a fixed text "Jan" or Dec" (I will enter it manually in the script), and xxxx is the original file extension).

I've tried to use the input for i in $(ls -tr) as it will be sorted by oldest date, and tried to replace the file names using basename $i, etc.

I have searched the net but my thick head could not come up with a working script.

1

1 Answer 1

1

Using what they say in this question and this blog post, you just move the file like this:

#!/bin/bash
prefix="YYY"
i=0
for file in $(ls -tr)
do
    filename=$(basename "$file")
    extension="${filename##*.}"
    paddedIndex=$(printf "%06d" $i)
    mv $file ${prefix}${paddedIndex}.${extension}
    i=$(($i + 1))
done
Sign up to request clarification or add additional context in comments.

2 Comments

awesome, it worked, but it can not handle spaces in the old file name.. many thanks "desert69"
@LoLo while IFS= read -r line; do echo "$line"; done <<< $(ls -rt files/)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.