2012-05-02 68 views
0

我想重命名我的目錄中的一堆文件,並將其卡在正則表達式部分。刪除perl中的字符串中的字符和數字

我想從一開始出現的文件名中刪除某些字符。

例1:_00-author--book_revision_

預計:Author - Book (Revision)

到目前爲止,我可以使用正則表達式來刪除下劃線& captialize的第一個字母

$newfile =~ s/_/ /g; 
$newfile =~ s/^[0-9]//g; 
$newfile =~ s/^[0-9]//g; 
$newfile =~ s/^-//g; 
$newfile = ucfirst($newfile); 

這不是一個好方法。在刪除所有字符之前,我需要幫助,直到您點擊第一個字母,並且當您點擊第一個' - '時,我想在' - '之前和之後添加一個空格。 此外,當我打第二個「 - 」我想「(」來代替它

任何引導,採取正確的方法技巧,甚至建議是非常讚賞

回答

1

所以你想要大寫新文件名的所有組件,或只是第一個?你的問題在這一點上是不一致的。

需要注意的是,如果你是在Linux上,你可能有rename命令,這將需要一個Perl的表達,並用它來爲你重命名文件,這樣的事情:

rename 'my ($a,$b,$r);$_ = "$a - $b ($r)" 
    if ($a, $b, $r) = map { ucfirst $_ } /^_\d+-(.*?)--(.*?)_(.*?)_$/' _* 
1

您的指示,你的榜樣唐。 「T匹配。

根據您的指示,

s/^[^\pL]+//; # Remove everything until first letter. 
s/-/ - /;  # Replace first "-" with " - " 
s/-[^-]*\K-/(/; # Replace second "-" with "(" 

根據你的榜樣,

s/^[^\pL]+//; 
s/--/ - /; 
s/_/ (/; 
s/_/)/; 
s/(?<!\pL)(\pL)/\U$1/g; 
+0

謝謝了! s/-/- /; < - 不會用' - '替換每個' - '?另外,如何在文件名的末尾添加')'? – Naveen

+0

我剛剛意識到我的錯誤。我有一些文件命名如上例所示,一些文件命名爲00-author-book-revision。無論哪種情況,我都希望將文件重命名爲Author - Book(修訂版)。但是你的輸入肯定幫助了我,我將找出如何解決這個問題。 – Naveen

+0

@Naveen,沒有/ g,它只會取代第一個。 ''s。=')';' – ikegami

0

如果它們都遵循這種格式然後嘗試:

my ($author, $book, $revision) = $newfiles =~ /-(.*?)--(.*?)_(.*?)_/; 

print ucfirst($author) . " - $book ($revision)\n"; 
1
$filename =~ s,^_\d+-(.*?)--(.*?)_(.*?)_$,\u\1 - \u\2 (\u\3),; 

我的Perl解釋器(使用嚴格和警告)說,這是更好的寫法如下:

$filename =~ s,^_\d+-(.*?)--(.*?)_(.*?)_$,\u$1 - \u$2 (\u$3),; 

第大概一個更多sedish它的味道! (當然,這兩個版本的作品一樣的。)

說明(如要求由stema):

$filename =~ s/ 
^  # matches the start of the line 
    _\d+- # matches an underscore, one or more digits and a hypen minus 
    (.*?)-- # matches (non-greedyly) anything before two consecutive hypen-minus 
      # and captures the entire match (as the first capture group) 
    (.*?)_ # matches (non-greedyly) anything before a single underscore and 
      # captures the entire match (as the second capture group) 
    (.*?)_ # does the same as the one before (but captures the match as the 
      # third capture group obviously) 
    $  # matches the end of the line 
/\u$1 - \u$2 (\u$3)/x; 

在替換指定的\u${1..3}只是告訴Perl從1將拍攝組3與他們的第一個人物造大寫。如果你想讓整個比賽(在一個被捕獲的組中)大寫,你必須改用\U

X標誌開啓詳細模式,它告訴我們要使用評論Perl解釋器,所以它會忽略這些(和正則表達式的任何空白 - 所以,如果你想匹配空間你必須使用\s\)。不幸的是,我無法弄清楚如何讓Perl忽略*替換*規範中的空白 - 這就是爲什麼我在一行中寫入的原因。

(另請注意,我已經改變了我s終止從,/ - Perl的咆哮在我,如果我用,用詳細模式開啓...不知道是什麼原因)

+0

+1教給我'\ u',但爲了讓它成爲一個真正的好答案,請解釋一下這裏發生了什麼。 – stema