Search code examples
bashrenamerecursive-queryparenthesesmv

rename recursively adding parenthere if folder name ending with 4 digits in bash


I have been trying to recursively rename folders whose names ends in four digits.

For example, I have a folder name like this:

this is the name 2004

and I'm trying to rename it to:

this is the name (2004)

I've tried to split the prefix and digit parts of the name however I cannot mv as rename these folder.

Here is the code I've tried so far:

#!/bin/bash
F=$(find . -name '*[0-9]' -type d)

for i in "$F";
do

R2=$(echo "$i" | awk '{print $NF}')
R1=$(echo "$i" | sed 's/.\{4\}$//')
R3=$(echo "$R2" | sed -r "s/(^[0-9]+$)/(\1)/g")

mv "$i" "$R1 $R3"
# Even tried:

mv "\"$i"\" "\"$R2 $R3"\"


done

Does anyone can review or/and suggest some guidance to allow mv to find the initial folder and its destination?


Solution

  • following command:

    find -name '*[0-9][0-9][0-9][0-9]' -type d -exec bash -c 'for dir; do mv "$dir" "${dir%[0-9][0-9][0-9][0-9]}(${dir#${dir%[0-9][0-9][0-9][0-9]}})"; done' - {} + -prune
    

    should work.

    • double quote arround variable expansion
    • ${dir%[0-9][0-9][0-9][0-9]} to remove last 4 digits suffix
    • ${dir#${dir%[0-9][0-9][0-9][0-9]}} to remove previous prefix
    • -exec bash -c '..' - {} + the - to skip the first argument after -c command which is taken for $0, see man bash /-c
    • -prune at the end to prevent to search in sub tree when matched, (suppose 2004/2004 then mv 2004/2004 "2004/(2004)" or mv 2004/2004 (2004)/2004' would fail)