Skip to main content

This bash script will locate and replace spaces in the filenames.

#!/usr/bin/env bash

## Example 1:

# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find . -type f | while read -r file; do
  # using POSIX class [:space:] to find space in the filename
  if [[ "$file" = *[[:space:]]* ]]; then
    # substitute space with "_" character and consequently rename the file
    mv "$file" "$(echo "$file" | tr ' ' '_')"
  fi
  # end of while loop
done

## Example 2:

##
# blank-rename: Renames filenames containing blanks
#
# Replace spaces with underscores in all the filenames in a directory.
#
# Source: https://tldp.org/LDP/abs/html/contributed-scripts.html#PETALS
##

ONE=1    # For getting singular/plural right (see below).
number=0 # Keeps track of how many files actually renamed.
FOUND=0  # Successful return value.

for filename in *; do           # Traverse all files in the current directory.
  echo "$filename" | grep -q " " # Check whether filename contains space(s).
  if [ $? -eq $FOUND ]; then
    fname=$filename                             # Yes, the filename needs work.
    newname=$(echo "$fname" | sed -e "s/ /_/g") # Substitute underscore for blank.
    mv "$fname" "$newname"                      # Do the actual renaming.
    ((number += 1))
  fi
done

if [ "$number" -eq "$ONE" ]; then # For correct grammar.
  echo "$number file renamed."
else
  echo "$number files renamed."
fi