Rename Files and Directories (Add Prefix)

后端 未结 10 1131
谎友^
谎友^ 2020-12-22 14:54

I would like to add prefix on all folders and directories.

Example:

I have

Hi.jpg
1.txt
folder/
this.file_is.here.png
another_folder.ok/
         


        
10条回答
  •  清酒与你
    2020-12-22 15:34

    Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use File::Copy;
    use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module
    
    die "Usage: $0 dir prefix" unless (@ARGV >= 2);
    my ($dir, $pre) = @ARGV;
    
    opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
    my @files = readdir($dir_handle);
    close($dir_handle);
    
    $CWD = $dir; # cd to the directory, needs File::chdir
    
    foreach my $file (@files) {
      next if ($file =~ /^\.+$/); # avoid folders . and ..
      next if ($0 =~ /$file/); # avoid moving this script if it is in the directory
    
      move($file, $pre . $file) or warn "Cannot rename file $file: $!";
    }
    

提交回复
热议问题