Managing Linux Filenames: Replacing Spaces with Underscores
Spaces in filenames are valid on Linux, but they can make shell scripting more cumbersome because paths must be quoted carefully. If a project has a naming convention that prefers underscores, you can rename files in batches with standard shell tools.
A Safe Bash Approach
The following script recursively finds files whose names contain spaces and replaces those spaces with underscores:
find . -type f -name "* *" -print0 | while IFS= read -r -d '' file; do
dir=$(dirname -- "$file")
base=$(basename -- "$file")
new=${base// /_}
[ "$base" = "$new" ] || mv -n -- "$file" "$dir/$new"
doneThe important details are:
-print0separates paths with a null byte, so filenames containing spaces, quotes, or newlines are handled safely.${base// /_}replaces every literal space in the basename with_.mv -navoids overwriting an existing destination file.--prevents filenames beginning with-from being interpreted as command options.
Preview Before Renaming
Before changing anything, preview the affected files:
find . -type f -name "* *" -printFor a single directory without recursion, a simpler loop works:
for file in *' '*; do
[ -e "$file" ] || continue
new=${file// /_}
printf '%s -> %s\n' "$file" "$new"
doneOnce the preview looks correct, replace the printf line with:
mv -n -- "$file" "$new"What About rename?
Many Linux distributions provide a command named rename, but there are multiple incompatible implementations. On systems with the Perl-based version, a command such as this may work:
rename 's/ /_/g' -- *' '*Check rename --version or its manual page before using a script copied from another distribution.
Do You Need to Remove Spaces?
Not necessarily. Well-written shell scripts can handle spaces safely by consistently quoting variables, for example:
cp -- "$source_file" "$destination"Renaming is mainly useful when your project, build system, URLs, or deployment workflow has a filename convention that excludes spaces.
Conclusion
Linux handles spaces in filenames correctly, but underscores can simplify automation and enforce a predictable naming convention. Preview changes first, quote paths properly, and avoid overwriting existing files during bulk renames.