1

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?

3 Answers 3

3

Try this:

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

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.

4
  • Sorry I forget to mention that I did use the ` symbol on line4. I change to ' because askubuntu use ` to represent code block and I can't seem to escape it. I used your suggested code, and no error is shown. But none of the directories is renamed.
    – Calvin
    Jun 11, 2015 at 3:40
  • I just posted an almost identical answer without realizing it was identical to this one. @Calvin This script works for me, make sure you're running it in bash (altough I guess some error should have come up): add the shebang (#!/bin/bash) and chmod +x script.sh && ./script.sh or simply run bash script.sh
    – kos
    Jun 11, 2015 at 4:41
  • Thanks thomasrutter & @kos. I manage to get it working by mv "$f" "$newd" (By adding the double quotes.)
    – Calvin
    Jun 11, 2015 at 4:43
  • 1
    @Calvin Indeed. The problem didn't come up in my test, because I tried using directories named as your example. Of course you want the ""
    – kos
    Jun 11, 2015 at 6:43
2

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' *

You must log in to answer this question.

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