繁体   English   中英

Bash - 重命名文件

[英]Bash — Renaming Files

我想编写一个脚本,通过几个不同的规则重命名大量文件。 我需要从某些字符串中删除一个特定的字符串,然后通过正则表达式重命名其他字符串(其中一些将是我之前从中删除字符串的字符串),然后根据文件名中的数字重命名其他字符串。

一般来说,假设我有多个目录(数百个),所有目录看起来都像这样:

1234-pic_STUFF&TOREMOVE_2000.tiff
1234-pic_STUFF&TOREMOVE_4000.tiff
1234-MORESTUFFTOREMOVE-012.jpg
1234-MORESTUFFTOREMOVE-037.jpg
1234-STUFF&TOREMOVE.pptx.pdf        (don't ask about this one)
1234-ET.jpg
1234-DF.jpg

对于一个看起来像:

1234_smallNum.tiff
1234_bigNum.tiff
1234_smallNum.jpg
1234_bigNum.jpg
1234_CaseReport.pdf
1234_ET.jpg
1234_DF.jpg

我已经有shell脚本使用perl脚本通过regex重命名(我把它关闭了,但我再也找不到它来引用它)。 它们就像remove_stuff_to_remove.shrename_case_reports.sh ,我可以cd到每个目录,并通过无输入调用它们来单独执行。

但是,我不知道如何根据数字转换文件名(2000和012到smallNum; 4000和037到bigNum;注意这些数字差别很大,所以我不能按范围或正则表达式进行;我必须将数字相互比较。)

而且我不知道如何自动化整个过程,这样我就可以从所有这些目录的根目录调用一个脚本,它将为我做所有这些事情。 我非常了解正则表达式,但是我在使用find命令或者通常使用shell脚本时效果不佳。

另外,我说Bash,但实际上,如果在Java,C,Python,Ruby或Lisp中做得更好,我知道这些语言要好得多,而且我只想在将这些文件转储到我之前找到解决方案(在接下来的一个月左右)......

真的 - 不要用bash折磨自己,只需使用你最喜欢的脚本语言。 以下内容将让您了解如何在Ruby中实现此目的。 急忙写的,所以请不要笑:

#!/usr/bin/env ruby

require 'find'

def move(path, old_name, new_suffix)
    number = old_name.sub(/^(\d+).*/,'\1')
    File.rename(path+'/'+old_name, path+'/'+number+'_'+new_suffix)
end

where_to_look = ARGV[0] || '.'
Find.find(where_to_look) do |dir|
    path = where_to_look+'/'+dir
    next if !File.directory?(path)
    entries = Dir.entries(path).select{|x| File.file?(path+'/'+x) }
    next if entries.size != 7

    %w(tiff jpg).each do |ext|
        imgs = entries.select{|x| x =~ /\d+\.#{ext}$/ }
        next if imgs.size != 2
        imgs.sort{|a,b| ai = $1.to_i if a =~ /(\d+)\.#{ext}$/ ; bi = $1.to_i if b =~ /(\d+)\.#{ext}$/ ; ai <=> bi }
        move(path, imgs.first, 'smallNum.'+ext)
        move(path, imgs.last, 'bigNum.'+ext)
    end
    report = entries.detect{|x| x =~ /\.pptx\.pdf$/ }
    move(path, report, 'CaseReport.pdf') if !report.nil?
    %w(ET DF).each do |code|
        file = entries.detect{|x| x =~ /^\d+-#{code}\.jpg$/ }
        move(path, file, code+'.jpg') if !file.nil?
    end
end

Bash的字符串替换:

$ match="foo"
$ repl="bar"
$ value="___foo___"
$ echo "${value/$match/$repl}"
___bar___

http://tldp.org/LDP/abs/html/string-manipulation.html

您可以将此模式应用于每个转换。

$ for file in $(find . -name "*-pic_STUFF\&TOREMOVE_2000.tiff"); do
    mv "$file" "${file/-pic_STUFF\&TOREMOVE_2000.tiff/_smallNum.tiff}"; done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM