Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace spaces in file names using a bash script

Can anyone recommend a safe solution to recursively replace spaces with underscores in file and directory names starting from a given root directory? For example:

$ tree . |-- a dir |   `-- file with spaces.txt `-- b dir     |-- another file with spaces.txt     `-- yet another file with spaces.pdf 

becomes:

$ tree . |-- a_dir |   `-- file_with_spaces.txt `-- b_dir     |-- another_file_with_spaces.txt     `-- yet_another_file_with_spaces.pdf 
like image 467
armandino Avatar asked Apr 25 '10 18:04

armandino


People also ask

How do you change underscore spaces in a filename in Linux?

Method 1: Through a single mv command Open your Ubuntu command line, the Terminal, either through the Application Launcher search or the Ctrl+Alt+T shortcut. When I listed the contents of the directory again, you can see that all file names now contain underscores instead of spaces.

How do you handle spaces in bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.

How do I replace text in a file in bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

I use:

for f in *\ *; do mv "$f" "${f// /_}"; done 

Though it's not recursive, it's quite fast and simple. I'm sure someone here could update it to be recursive.

The ${f// /_} part utilizes bash's parameter expansion mechanism to replace a pattern within a parameter with supplied string. The relevant syntax is ${parameter/pattern/string}. See: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html or http://wiki.bash-hackers.org/syntax/pe .

like image 104
Naidim Avatar answered Oct 10 '22 10:10

Naidim