Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove spaces from all the file-names in the current directory

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.
like image 356
Gautam Avatar asked Sep 07 '12 08:09

Gautam


3 Answers

for i in * ; do 
  if [ "$i" != ${i//[[:space:]]} ] ; 
  then
    mv "$i" "${i//[[:space:]]}"
  fi
done

${i//[[:space:]]} removes all the spaces in a string.

like image 197
Gautam Avatar answered Oct 11 '22 21:10

Gautam


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));
        }
    }
}
like image 43
Nahuel Fouilleul Avatar answered Oct 11 '22 22:10

Nahuel Fouilleul


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"))}'
like image 2
glenn jackman Avatar answered Oct 11 '22 22:10

glenn jackman