Bash - 重命名文件

时间:2013-11-14 19:01:27

标签: regex linux bash shell

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

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

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

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

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

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

另外,我说Bash,但实际上,如果在Java,C,Python,Ruby或Lisp中做得更好,我对这些语言的了解要好得多,而且在得到这些文件之前我只想要解决这个问题。倾倒在我身上(在接下来的一个月左右)......

2 个答案:

答案 0 :(得分:1)

真的 - 不要用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

答案 1 :(得分:1)

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
相关问题