Remove space from a filename

573 views Asked by At

I am stuck at finding an answer to my question, so i made windows-cmd like program and one of my feature is to rename a file. Everything is fine if theres no whitespace in the old name / new name, but as long as theres a space it simply doesn't work. I've been looking on how to remove the whitespaces from both old and new names (if theres one), then proceed to rename and put the whitespace back but i've no idea on how to proceed.. I've been reading a few things about "trim" but it doesn't help. Here is the part of my code :

elsif ($fr eq 'ren') {
        $getmenu =~ s/ren //g;
        my ($rf,$kb) = split /[ ]/,$getmenu;
        rename($rf, $kb) || die "Error\n";
        print "\n>$rf has been renamed as $kb\n";
    }
2

There are 2 answers

1
Phil Cazella On BEST ANSWER

Since the white space character is a problem, I would:

  1. replace them with a placeholder symbol (like a hyphen, pipe, or @)
  2. rename the file
  3. replace the placeholder symbol with spaces again

This question shows how to do that: Replace whitespace with hyphen in Perl

0
ikegami On

You use spaces to indicate where the file names start and end, so there can't possibly be any spaces in the names. That's why shells use quoting and escaping mechanisms. You need to introduce those into your command language.