Amila Senadheera
Amila Senadheera

Reputation: 13245

How to rename(by adding a prefix) all the files and folders starting from the current folder?

I could write the following script to get it done. But it is not working perfectly for my case.

CCUSTOMER_NAME="Abcd"
PATHS=$(find . -name "Template*")

echo $path

for path in $PATHS
do
    name=$(basename $path)
    newname=${CUSTOMER_NAME}"$(echo "$name" | cut -c9-)"
    mv "$name" "$newname"
done

I have a folder structure like below.

-/TemplateProjectA
-/TemplateProjectB
   -/TemplateFiles
     -/TemplateMyFile.xml
-/TemplateProjectC

Currently, it gives the output as below

-/<CUSTOMER_NAME>ProjectA
-/<CUSTOMER_NAME>ProjectB
   -/TemplateFiles
     -/TemplateMyFile.xml
-/<CUSTOMER_NAME>ProjectC

As you can see it has missed two files giving the below error.

mv: cannot stat 'TemplateFiles': No such file or directory
mv: cannot stat 'TemplateMyFile.xml': No such file or directory

The reason is, I first list paths to the folders/files starting with "Template". But it renames the outer folder first and unable to locate the inner files/folders. I could not find anywhere a similar sinario properly described.

Any help is much apprecaited!!

Upvotes: 1

Views: 113

Answers (1)

Thomas
Thomas

Reputation: 17422

The problem that outer folders are renamed first can be prevented by sorting all candidate files/directories in reverse order first:

MATCH=Template
REPLACEMENT=Abcd

find -name "${MATCH}*" | sort -r | while read path; do
    newname=$(basename ${path} | sed "s/${MATCH}/${REPLACEMENT}/")
    mv "${path}" "$(dirname ${path})/${newname}"  
done

Upvotes: 2

Related Questions