linux - How to replace spaces in file names using a bash script

ID : 10029

viewed : 32

Tags : linuxbashwhitespacefilenameslinux

Top 5 Answer for linux - How to replace spaces in file names using a bash script

vote vote

91

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 .

vote vote

89

Use rename (aka prename) which is a Perl script which may be on your system already. Do it in two steps:

find . -name "* *" -type d | rename 's/ /_/g'    # do the directories first find . -name "* *" -type f | rename 's/ /_/g' 

Based on J├╝rgen's answer and able to handle multiple layers of files and directories in a single bound using the "Revision 1.5 1998/12/18 16:16:31 rmb1" version of /usr/bin/rename (a Perl script):

find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \; 
vote vote

76

find . -depth -name '* *' \ | while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done 

failed to get it right at first, because I didn't think of directories.

vote vote

68

you can use detox by Doug Harple

detox -r <folder> 
vote vote

51

A find/rename solution. rename is part of util-linux.

You need to descend depth first, because a whitespace filename can be part of a whitespace directory:

find /tmp/ -depth -name "* *" -execdir rename " " "_" "{}" ";" 

Top 3 video Explaining linux - How to replace spaces in file names using a bash script

Related QUESTION?