Ubuntu: Rename directory using a variable



Question:

I have a directory that contains thousands of sub-directories. Structure like this:

Dirs:

  • 1
  • 2
  • 30
  • 109

I want to rename all the directories by adding 10000 to their current name. E.g.

Dirs:

  • 10001
  • 10002
  • 10030
  • 10109

I have written this script

for f in *; do      if [[ -d $f ]]; then          echo $f          newd='expr $f + 10000'          echo $newd          mv $f newd      fi  done  

from the 2 echos, I can see 1 and 10001. But the mv actually move all my directories into a new folder called newd. I tried $newd, doesn't work as well.

What could be done to make this thing works?


Solution:1

What if you do this?

for f in *; do      if [[ -d $f ]]; then          echo $f          newd=`expr $f + 10000`          echo $newd          mv "$f" "$newd"      fi    done  

That is, change the quote marks around expr $f + 10000 to backticks so they're executed in place and the result is stored in the variable. Also make sure to have the dollar sign on $newd on the mv line.

I'm not 100% sure of myself so make sure to backup before you try or try on some test files/dirs.

Edit: added double quotes to answer as they turned out to be required.


Solution:2

Try this:

for f in *; do       if [[ -d $f ]] ; then           mv "$f"  $(($f + 1000))      fi  done  


Solution:3

You can also use rename:

for f in *; do       [ -d "$f" ] && rename -n 's/$_/$_+1000/e' "$f"  done  

If you want to rename every file or directory, just run:

rename -n 's/$_/$_+1000/e' *  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »