up vote 0 down vote favorite
share [g+] share [fb]

How do I rename 2009-08-2009-08-13 to 2009-08-$my_var_till_2009-08-13 for multiple files? The 2009-08-13 portion changes with respect to the date of the file, so I need a way to grab that part of the filename. Could I use basename somehow?

link|improve this question
1  
on what OS? – John T Sep 21 '09 at 0:55
I am running this on a Linux OS – bisnez Sep 21 '09 at 0:59
feedback

3 Answers

If the file names are always in that date format, I think that something like this would work (in a script) - this is, of course, assuming that they are all in the same directory and '$my_var_till' is defined in the shell:

#!/bin/bash

cd <name_of_target_directory>

for i in `ls`
do
    yyyy=`echo $i | awk -F- '{print $3}`'
    mm=`echo $i | awk -F- '{print $4}'`
    dd=`echo $i | awk -F- '{print $5}'`

    mv $i "$yyyy-$mm-$my_var_till-$yyyy-$mm-$dd"
done

if '$my_var_till' is not defined in the shell, you could take it as a command line argument (of course you might want to add some error checking with the argument):

#!/bin/bash

my_var_till=$1
<continue on with code from above>
link|improve this answer
feedback

mmv can help

link|improve this answer
feedback

Linux:

obligatory 1-liner...

for i in `ls`;do echo $i | awk -F- '{print "mv "$1"-"$2"-"$3"-"$4"-"$5" "$1"-"$2"-""'"$my_var_till"'""-"$3"-"$4"-"$5}';done

expanded

#!/bin/bash
my_var_till=somevalue  # can replace with $1 to use command-line arg to script
for i in `ls`
     do echo $i | awk -F- '{print "mv "$1"-"$2"-"$3"-"$4"-"$5" "$1"-"$2"-""'"$my_var_till"'""-"$3"-"$4"-"$5}'
done

you could also use the rename command and supply a Perl regex.

assuming your variable is a variable you have set in the shell, which is what I think you're asking.

Windows:

rename 2009-08* 2009-08-%my_var_till%_*
link|improve this answer
feedback

Your Answer

 
or
required, but never shown