Search code examples
bashfile-renamerenaming

rename a set of files, by changing their prefix


I've got a set of four directories

 English.lproj
 German.lproj
 French.lproj
 Italian.lprj

each of this contains a serie of XMLs named

 2_symbol.xml
 4_symbol.xml
 5_symbol.xml
 ... and so on ...

I need to rename all of these files into another numerical pattern, because the code that determined those numbers have changed. so the new numerical pattern would be like

 1_symbol.xml
 5_symnol.xml
 3_symbol.xml
 ... and so on ...

so there's no algorithm applicable to determine this serie, because of this reason I thought about storing the two numerical series into an array.

I was thinking to a quick way of doing it with a simple bash script. I think that I'd need an array to store the old numerical pattern and another array to store the new numerical pattern, so that I can perform a cycle to make

 # move n_symbol.xml newdir/newval_symbol.xml

any suggestion?

thx n cheers.

-k-


Solution

  • you don't need bash for this, any POSIX-compatible shell will do.

    repls="1:4 2:1 4:12 5:3"
    
    for pair in $repls; do
      old=${pair%:*}
      new=${pair#*:}
      file=${old}_symbol.xml
      mv $file $new${file#$old}
    done
    

    edit: you need to take care of overwriting files. the snippet above clobbers 4_symbol.xml, for example.

    for pair in $repls; do
      ...
      mv $file $new${file#$old}.tmp
    done
    for f in *.tmp; do
      mv $f ${f%.tmp}
    done