As the title suggests how do I remove spaces from all the files in the current directory ?
Example
file name.mp3
should become filename.mp3
Note:
- I am open to an answer in any language.
As the title suggests how do I remove spaces from all the files in the current directory ?
Example
file name.mp3
should become filename.mp3
Note:
I am a big fan of python, so here is a python script for doing the same
import os
for f in os.listdir("."):
r = f.replace(" ","")
if( r != f):
os.rename(f,r)
with sh
for file in *' '*; do [ -f "$file" ] && mv "$file" "`echo $file|tr -d '[:space:]'`"; done
with perl 5.14 (replace y/ //dr
by do{($x=$_)=~y/ //d;$x}
for older versions)
# Linux/Unix
perl -e 'rename$_,y/ //drfor<"* *">'
# Windows
perl -e "rename$_,y/ //drfor<'* *'>"
with Java
import java.io.File;
public class M {
public static void main(String[] args) {
String o,n;
for (File old : new File(".").listFiles()) {
o=old.getName();
if (!o.contains(" ")) continue;
n=o.replaceAll(" ", "");
old.renameTo(new File(n));
}
}
}
mv "$file" $(tr -d '[:space:]' <<< $file)
-- since we're removing whitespace, we don't have to worry about quoting the new file name.
Sep 7, 2012 at 10:49
for i in * ; do
if [ "$i" != ${i//[[:space:]]} ] ;
then
mv "$i" "${i//[[:space:]]}"
fi
done
${i//[[:space:]]}
removes all the spaces in a string.
bash
? They are two different shells.
bash
. The distinction is quite relevant.
Since you're language agnostic, here's a ruby one-liner:
ruby -e 'Dir.foreach(".") {|f| f.count(" \t") > 0 and File.rename(f, f.delete(" \t"))}'
ls -1 | awk '/ /{a=$0;gsub(/ /,"");b="mv \""a"\" "$0;system(b);}'
ls -1 | awk '/ /{a=$0;gsub(/ /,"");b="mv \""a"\" "$0;system(b);}' /bin/sh: 1: Syntax error: "(" unexpected /bin/sh: 1: Syntax error: "(" unexpected /bin/sh: 1: Syntax error: "(" unexpected
Throws the above errors
This renames an old file only if the old file name contained a space and the new file doesn't already exist.
for old in *; do
new="${old//[[:space:]]}"
[[ $old = $new || -f $new ]] || mv "$old" "$new"
done
file name a.mp3
andfilename a.mp3
.