Cybersecurity Updates & Tools

How to Rename Directories in Linux: mv, Loops, and rename

Linux provides two main tools for renaming directories: mv for single renames and the rename utility for batch pattern-based operations.

How to Rename a Directory in Linux

The mv command handles directory renames:

bashmv dir1 dir2

The first argument is the current name and the second is the new name.

If dir2 already exists as a directorymv moves dir1 inside it instead of renaming it. Use -i to get a confirmation prompt before that happens:

bashmv -i dir1 dir2

Add -v for verbose output that confirms what was renamed:

bashmv -v dir1 dir2# renamed 'dir1' -> 'dir2'

For a directory not in the current working directory, specify the full path:

bashmv /home/user/dir1 /home/user/dir2

Rename Multiple Directories with a Loop

mv renames one directory at a time. For batch operations, combine it with a Bash for loop:

bashfor d in *; do  if [ -d "$d" ]; then    mv -- "$d" "${d}_$(date +%Y%m%d)"  fidone

The glob * matches everything in the current directory. The [ -d "$d" ] test filters out regular files so only directories are renamed. The -- before the variable protects against directory names starting with - being read as flags by mv. This example appends a date stamp in YYYYMMDD format to each directory name.

The same result using find:

bashfind . -mindepth 1 -prune -type d -exec sh -c 'd="{}"; mv -- "$d" "${d}_$(date +%Y%m%d)"' \;

-mindepth 1 excludes the current directory (.) from results. -prune prevents find from descending into subdirectories — only top-level directories are matched.

Batch Rename with the rename Command

The rename command renames multiple entries using Perl’s transliteration operator. To replace every space in directory names with an underscore:

bashfind . -mindepth 1 -prune -type d | rename 'y/ /_/'

To convert all directory names to lowercase:

bashfind . -mindepth 1 -prune -type d | rename 'y/A-Z/a-z/'

Always preview with -n before applying changes to real data:

bashfind . -mindepth 1 -prune -type d | rename -n 'y/ /_/'

-n prints what would be renamed without making any changes.

Use mv for single renames, a for loop for batch operations with custom logic, and rename -n to preview pattern changes before applying them. Leave a comment below if you run into any issues.