views:

211

answers:

3

I'd like to rename some files that are all in the same directory. The file name pattern used is Prefix_ddmmyy.tex with a european date format. For the sake of readability and the ordering I'd like to rename the files in a pattern Prefix_yymmdd.tex with a canonical date format.

Anyone ideas how I can do this automatically for a complete directory? My sed and regexp knowledge is not very sharp...

+3  A: 

Hi,

for file in Prefix_*.tex ; do
  file_new=`echo "$file" | sed -e 's:\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)\(\.tex\):\3\2\1\4:'`
  test "$file" != "$file_new" && mv -f "$file" "$file_new"
done

Or, if you have a lot of files and/or want to process files recursively, replace:

for file in Prefix_*.tex ; do

with:

find . -name Prefix_*.tex -print | while read file ; do

or (non-recursive, GNU):

find . -maxtdepth 1 -name Prefix_*.tex -print | while read file ; do

Cheers, V.

vladr
A: 

You can try "mmv".

Aaron Digulla
+1  A: 

You can also do it with any bourne-type shell without external commands:

for f in *.tex; do
  _s=.${f##*.} _f=${f%.*} _p=${f%_*}_ 
  _dt=${_f#$_p} _d=${_dt%????} _m=${_dt%??} 
  _y=${_dt#$_m} _m=${_m#??}
  mv -- "$f"  "$_p$_y$_m$_d$_s"
done

With zsh it would be:

 autoload -U zmv
 zmv '(*_)(??)(??)(??)(.tex)' '$1$4$3$2$5'
radoulov
I understand the solution from Vlad, but can you explain what your script does. I don't understand the binding of the different variables.
boutta