Rename Files and Directories (Add Prefix)

后端 未结 10 1080
谎友^
谎友^ 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: $!";
    }
    
    0 讨论(0)
  • 2020-12-22 15:37

    with Perl:

    perl -e 'rename $_, "PRE_$_" for <*>'
    
    0 讨论(0)
  • 2020-12-22 15:44

    Thanks to Peter van der Heijden, here's one that'll work for filenames with spaces in them:

    for f in * ; do mv -- "$f" "PRE_$f" ; done
    

    ("--" is needed to succeed with files that begin with dashes, whose names would otherwise be interpreted as switches for the mv command)

    0 讨论(0)
  • 2020-12-22 15:44

    On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

    for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done
    
    0 讨论(0)
提交回复
热议问题