shellfindrename

How to use find and prename to reformat directory names recursively?


I am trying to find all directories that start with a year in brackets, such as this:

[1990] Nature Documentary

and then rename them removing brackets and inserting a dash in between.

1990 - Nature Documentary

The find command below seems to find the results, however I could not prefix the pattern with ^ to mark start of directory name otherwise its not returning hits.

I am pretty sure I need to use -exec or -execdir, but I am not sure how to store the found pattern and manipulate it.

find . -type d -name '\[[[:digit:]][[:digit:]][[:digit:]][[:digit:]]] *'

Solution

  • With [p]rename:

    -depth -exec prename -n 's/\[(\d{4})]([^\/]+)$/$1 -$2/' {} +
    

    Drop -n if the output looks good.

    Without it, you'd need a shell script with several hardly intelligible parameter expansions there:

    -depth -exec sh -c '
    for dp; do
      yr=${dp##*/[} yr=${yr%%]*}
      echo mv "$dp" "${dp%/*}/$yr -${dp##*/\[????]}"
    done' sh {} +
    

    Remove echo to apply changes.