0

I am trying to bulk rename many folders but for some reason my approach does not seem to work. I am trying to use the following script but it does nothing. I am new to programming so any suggestions are appreciated. These are the folder names that i have.

test.custom.tmp         untitledfolder.custom.tmp   wis.custom.tmp

I need them renamed to

test untitledfolder wis

I am using the following script but it does nothing.

while read line; do
  newname=$(echo "$line" | cut -f 1 -d '_')
  mv $line newname;
done < read

Here i created a file called read with all the foldernames that need renaming.

What is wrong with this script and also is there a better way to get this done? Thanks.

7

2 Answers 2

2

A simple way would be:

$ for d in *.custom.tmp/; do 
    echo mv -- "$d" "${d%%.*}"
  done
mv -- test.custom.tmp/ test
mv -- untitledfolder.custom.tmp/ untitledfolder
mv -- wis.custom.tmp/ wis

Once you are sure that's the result you want, remove the echo.


The ${d%%.*} is a parameter expansion, precisely:

${parameter%word}

${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted.

In this case it takes the string for example test.custom.tmp and removes everythig after the first ..

4
  • 1
    One may possibly want to restrict the loop to *.custom.tmp/, if there are other names containing dots in the directory.
    – Kusalananda
    Commented May 31, 2022 at 15:50
  • Good, added to the answer @Kusalananda. Commented May 31, 2022 at 15:58
  • Hi thanks for the answer. I have seen ${d%%.*} type of code before on the internet . can you please explain how this works? I mean what this %% is supposed to mean and how it knows to remove .custom.tmp instead of just .tmp Commented Jun 2, 2022 at 0:53
  • @ranjitabraham You are welcome, added an explanation from the bash manual in the answer. Commented Jun 2, 2022 at 3:00
1

If you want to keep your aproach, you can do something like:

while read line; do
  newname=$(echo "$line" | cut -f 1 -d '.');
  mv $line $newname;
done < read

Just keep in mind that your delimiter is a point (-d '.'), and also use the $newname as a variable, not as a string.

This corrects your scripts errors, but for a better approach you can use @schrodingerscatcuriosity answer.

2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .