Blog / Others/ Linux Shell Script: Safely Batch Rename Files by Replacing Spaces and Special Characters

Linux Shell Script: Safely Batch Rename Files by Replacing Spaces and Special Characters

Linux Shell 脚本:安全批量替换文件名中的空格与特殊字符

Linux Shell Script: Safely Batch Replace Spaces and Special Characters in Filenames

In Linux, filenames containing spaces, parentheses, commas, or other special characters can cause issues in command-line operations and script processing. This script standardizes filenames in the current directory by performing the following actions:

  1. Replace all spaces (including multiple consecutive spaces) with a single dot ..
  2. Replace parentheses (, ), square brackets [, ], and commas , with underscores _.
  3. Collapse multiple consecutive dots or underscores into a single character.

This results in cleaner, safer filenames that are less likely to cause parsing errors.

Script Code

Save the following as a file (e.g., rename_files.sh) and make it executable.

#!/bin/bash

find . -maxdepth 1 -name '*' -print | while read -r name; do
    if [ "$name" = "." ]; then
        continue
    fi

    newname=$(echo "$name" |
        sed 's/s+/./g' |
        sed 's/[(,)]/_/g' |
        sed 's/[/_/g' |
        sed 's/]/_/g' |
        sed 's/.{2,}/./g' |
        sed 's/_{2,}/_/g')

    if [ "$name" != "$newname" ]; then
        echo "mv "$name" "$newname""
        mv "$name" "$newname"
    fi
done

echo "Renaming complete."

Key Improvements

  • Uses bash for better compatibility.
  • Uses read -r to prevent backslash interpretation.
  • Skips the current directory entry (.).
  • Corrected variable names and quoted mv arguments for safety with spaces.
  • Added a completion message.

Usage Instructions

  1. Open a terminal and navigate to the target directory.
  2. Save the script as rename_files.sh.
  3. Make it executable: chmod +x rename_files.sh
  4. Dry run first: Comment out the mv line (add # at the start) and run the script to preview changes.
  5. If the output is correct, uncomment the mv line and run the script again to perform the rename.

Warning: Batch renaming is irreversible. Always back up important files or test the script in a safe directory first.

Post a Comment

Your email will not be published. Required fields are marked with *.