Search code examples
linuxbashmv

Batch file rename where part of the old name became directories


I don't know if this is possible using bash but it would be nice to be able to do this just using bash.

I receive bunch of files (regularly) with the following name pattern:

  • xxx___yyy___abc__def.pdf
  • xxxa___y_yy___fg-h___ijdfdak.pdf
  • xx___v-vv___a_fasl-bk___os___23l.pdf
  • etc.

And I need to rename and move them into directories:

  • ~/xxx/yyy/abc/def.pdf
  • ~/xxxa/y_yy/fg-h/ijdfdak.pdf
  • ~/xx/v-vv/a_fasl-bk/os/23l.pdf

Is it possible? Please help.


Solution

  • Using parameter expansion.

    #!/bin/sh
    
    for f in *.pdf; do
      last=${f##*_} first=${f%%_*} 
      third=${f%$last*} third="${third%??*}"
      third=${third##*_} second=${f%$third*}
      second=${second%???*} second=${second##*_}
      echo mkdir -p ~/"$first/$second/$third" && \                                                                                                                                               
      echo mv -v "$f" ~/"$first/$second/$third/$last"
    done
    

    As per update of the OP's question. Should remove all underscores.

    #!/bin/bash
    
    for f in *.pdf; do
      new=$(awk -F'[_]+' -vOFS='/' '{$1=$1}1' <<< "$f")
      echo mkdir -p ~/"${new%/*}/" && \
      echo mv -v "$f"  ~/"$new"
    done
    
    • Remove the echo to actually rename the files.

    The actual out put without the echo

    copied 'xx___v-vv___a_fasl-bk__os23l.pdf' -> '/home/Pelangi/xx/v-vv/a/fasl-bk/os23l.pdf'
    removed 'xx___v-vv___a_fasl-bk__os23l.pdf'
    copied 'xxxa___y_yy___fg-h__ijdfdak.pdf' -> '/home/Pelangi/xxxa/y/yy/fg-h/ijdfdak.pdf'
    removed 'xxxa___y_yy___fg-h__ijdfdak.pdf'
    copied 'xxx___vvv___abk__osl.pdf' -> '/home/Pelangi/xxx/vvv/abk/osl.pdf'
    removed 'xxx___vvv___abk__osl.pdf'
    copied 'xxx___yyy___abc__def.pdf' -> '/home/Pelangi/xxx/yyy/abc/def.pdf'
    removed 'xxx___yyy___abc__def.pdf'
    copied 'xxx___yyy___fgh__ijk.pdf' -> '/home/Pelangi/xxx/yyy/fgh/ijk.pdf'
    removed 'xxx___yyy___fgh__ijk.pdf'