Linux - Replacing spaces in the file names
I have a number of files in a folder, and I want to replace every space character in all file names with underscores. How can I achieve this?
Solution 1:
This should do it:
for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
Solution 2:
I prefer to use the command 'rename', which takes Perl-style regexes:
rename "s/ /_/g" *
You can do a dry run with the -n flag:
rename -n "s/ /_/g" *
Solution 3:
Use sh...
for i in *' '*; do mv "$i" `echo $i | sed -e 's/ /_/g'`; done
If you want to try this out before pulling the trigger just change mv
to echo mv
.
Solution 4:
If you use bash:
for file in *; do mv "$file" ${file// /_}; done
Solution 5:
What if you want to apply the replace task recursively? How would you do that?
Well, I just found the answer myself. Not the most elegant solution, (also tries to rename files that do not comply with the condition) but it works. (BTW, in my case I needed to rename the files with '%20', not with an underscore)
#!/bin/bash
find . -type d | while read N
do
(
cd "$N"
if test "$?" = "0"
then
for file in *; do mv "$file" ${file// /%20}; done
fi
)
done