When managing files on Linux, it is common to encounter directories or filenames that contain spaces. While spaces are valid characters, they often complicate command-line operations, scripting, and automation. Many developers prefer using underscores instead to avoid quoting or escaping filenames. This tutorial explains how to replace spaces with underscores in filenames on Linux.
First, create a sample directory layout that includes spaces in both directory and filenames:
mkdir -p 'my_dir/test 1' 'my_dir/test 2'
touch 'my_dir/test 1/file 1.txt' 'my_dir/test 2/file 2.txt'
Directory tree:
my_dir
|-- test 1
| |-- file 1.txt
|-- test 2
|-- file 2.txt
To replace spaces with underscores recursively in the ./my_dir directory, we can run the following command:
find ./my_dir -depth -name "* *" -execdir bash -c 'mv "$0" "${0// /_}"' {} \;
After running the command, the directory structure becomes:
my_dir
|-- test_1
| |-- file_1.txt
|-- test_2
|-- file_2.txt
Let's examine how the command works:
find ./my_dir- begins scanning inside the./my_dirdirectory.-depth- processes files before their parent directories. This is important when renaming directories so their contents are handled first.-name "* *"- selects only entries whose names contain a space.-execdir ... {} \;- runs the specified command within the directory where the match was found.bash -c 'mv "$0" "${0// /_}"'- invokes a Bash command that renames the file or directory."$0"- represents the current filename passed byfind."${0// /_}"- performs Bash parameter substitution, replacing every space with an underscore.
Leave a Comment
Cancel reply