LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash Script - adding file modification date to end of filenames in directory (https://www.linuxquestions.org/questions/programming-9/bash-script-adding-file-modification-date-to-end-of-filenames-in-directory-751920/)

themonkman 09-01-2009 06:02 PM

Bash Script - adding file modification date to end of filenames in directory
 
Hello all,

I'm not adept at bash scripting, but I need to find a way to take a group of files in a directory and add their file modification dates to the end of the filename. For example I have:

LogDir/

-rw-r----- 1 test users 0 Aug 1 21:50 test.log.1
-rw-r----- 1 test users 0 Aug 3 21:50 test.log.2
-rw-r----- 1 test users 0 Aug 5 21:50 test.log.3
-rw-r----- 1 test users 0 Aug 7 21:50 test.log.4
-rw-r----- 1 test users 0 Aug 8 21:50 test.log.5

And I need the script to convert the all the files in the directory to:

LogDir/

-rw-r----- 1 test users 0 Aug 1 21:50 test.log.20090801
-rw-r----- 1 test users 0 Aug 3 21:50 test.log.20090803
-rw-r----- 1 test users 0 Aug 5 21:50 test.log.20090805
-rw-r----- 1 test users 0 Aug 7 21:50 test.log.20090807
-rw-r----- 1 test users 0 Aug 9 21:50 test.log.20090809

Any help would be greatly appreciated. I'm just starting to learn bash scripting but I still have a long way to go.

unSpawn 09-01-2009 06:40 PM

Code:

# find in directory "LogDir" all items of type "file" with name glob "test.log.*",
find LogDir -type f -iname test.log.\* | while read FILE; do
 # Use 'stat' to extract the modification time,
 mtime=($(stat -c "%y" "${FILE}"))
 # Prepare the new filename chopping off numbering,
 NFILE="${FILE//g.*/g.}"
 # Propose renaming
 echo mv "${FILE}" "${NFILE}.${mtime[0]//-/}"
done

Run, and if you think this'll work change "echo mv" to read just "mv".

Code:

function help() { echo "Bash scripting guides:
http://www.tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html
http://www.tldp.org/LDP/Bash-Beginners-Guide/html/index.html
http://www.tldp.org/LDP/abs/html/"; }


themonkman 09-01-2009 11:45 PM

Thank you so much! That worked perfectly.


All times are GMT -5. The time now is 03:59 PM.