Results 1 to 3 of 3
Hi everybody,
I need to rename files adding a timestamp to there name.
eg : rename myfile in myfile-2008-03-05
I need to do that on every file in a directory ...
- 03-05-2008 #1Just Joined!
- Join Date
- Mar 2008
- Posts
- 11
Advanced file renaming
Hi everybody,
I need to rename files adding a timestamp to there name.
eg : rename myfile in myfile-2008-03-05
I need to do that on every file in a directory and its subdirectories.
So I wrote the following script :
It seems to work fineCode:find * -type f -exec mv "{}" "{}-2008-05-03" \;
Now, most of my directories store windows clients files. Which means those files have extensions and users see them with icons corresponding to this extension.
That's why I'd like to run my script adding the timestamp before the extension
eg : rename report.xls in report-2008-03-05.xls
Does anyone have a brilliant idea to do so ?
Thanks for your help.
Santiago
- 03-05-2008 #2Linux User
- Join Date
- Jun 2007
- Posts
- 318
You'd have to write a script. Here's one I came up with that seems to work. Use at your own risk:
Note that if you run this script a 2nd time on a directory you'll get files like:Code:#!/bin/bash typeset -i len shopt -s extglob curdte="`date "+%Y-%m-%d"`" for oldfle in $(find * -type f) do dir="`dirname $oldfle`" fle="`basename $oldfle`" tmp="${fle%.*([[:alnum:]])}" len=${#tmp} lft="`echo "$fle^$len" | awk -F^ '{print substr($1,1,$2)}'`" len=len+1 rt="`echo "$fle^$len" | awk -F^ '{print substr($1,$2)}'`" newfle="${dir}/${lft}-${curdte}${rt}" echo $oldfle echo $newfle mv $oldfle $newfle done
report-2008-03-05-2008-30-05.xls
Edit: Note that if there are spaces in the filenames this script will break.
- 03-06-2008 #3Linux Guru
- Join Date
- Nov 2007
- Location
- Córdoba (Spain)
- Posts
- 1,513
This should work, not tested though.
If a file is on the form a.b, it ends as a-<date>.b.Code:#!/bin/bash DATE="$(date "+%Y-%m-%d")" find * -type f | while read file do ext="${file##*.}" if [ ! "$file" == "$ext" ] then old="${file%.${ext}}" new="${old}-${DATE}.${ext}" else new="${file}-${DATE}" fi echo $new done
If a file is on the form a.b.c, it ends as a.b-<date>.c
if a file has no extension, it ends being called a-<date>


Reply With Quote