当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - Perl one-liner to add a string at the end of file name

问题描述:

I have some HTML and JavaScript files in a directory. I want to append "_backup" at the end of each JavaScript (name.js) file. What would be the one-liner for it?

网友答案:

Pick your poison:

  1. File::Copy

    use File::Copy 'move';
    for ( glob "*.js" ){  # Platform independent
        move( $_, "${_}_backup" ) or warn "Failed to copy '$_'";
    }
    
  2. rename function

    for ( glob "*.js" ){   # Not platform independent
        rename( $_, "${_}_backup" ) or warn "Failed to copy '$_'";
    }
    
  3. The *nix rename utility

    $ rename .js .js_backup *.js
    
网友答案:

-i option creates the backup file with the given suffix, and then you give an empty script.

perl -i_backup -p -e "" *.js; rm *.js

that's actually a two-liners

Thanks to Zaid's answer:

perl -e 'rename($_,$_."_backup") for (glob "*.js");'
网友答案:

This a slightly long line, but it is a Perl one-liner!

I assume you want files named

abc.js
def.js
dog.js

to be renamed to

abc_backup.js
def_backup.js
dog_backup.js

perl -e 'for(@ARGV) { ($bname)=/(.*)\.js/; rename $_, "$1_backup.js"; } ' *js

Most Linux distributions include a program "rename" which is actually written in Perl and does renaming operations like this; see man rename.

分享给朋友:
您可能感兴趣的文章:
随机阅读: