2017-04-26 65 views
1

我是新的Perl腳本,我想刪除一些字符,可以在一行的開頭。我想刪除的字符@和/或=perl刪除前導@和=一行

這裏是一個文件例如:

@word <= Remove @ 
=word <= Remove = 
@=word <= Remove @ AND = 
[email protected] <= Remove = AND @ 
[email protected][email protected][email protected][email protected]@word <= Remove all the = and @ 

目前,我用substr($line, 0, 1, " ") if "@" eq substr($line, 0, 1);但它僅刪除第一個@。我如何編輯這一行,以便刪除所有前導@=

回答

6

這樣做是有substr是一個很大的開銷。只需使用s///進行正則表達式替換即可。

while (my $line = <DATA>) { 
    $line =~ s/^[@=]+//; 
    print $line; 
} 

__DATA__ 
@word <= Remove @ 
=word <= Remove = 
@=word <= Remove @ AND = 
[email protected] <= Remove = AND @ 
[email protected][email protected][email protected][email protected]@word <= Remove all the = and @ 

圖案這裏是/^[@=]+/,這意味着字符串的開頭_The,然後一個或多個任一或@=。您可以使用該模式的regex101.com for a more detailed explanation。它會將它們刪除,就像您的問題所述。

輸出是:

word <= Remove @ 
word <= Remove = 
word <= Remove @ AND = 
word <= Remove = AND @ 
word <= Remove all the = and @ 

如果你想,而不是用空格代替像你的代碼一樣,你需要做更復雜的東西。

s/^([@=]+)/" "x length $1/e; 

該解決方案suggested by Tanktalus利用了/e改性劑,它可以讓你把Perl代碼在s///的替代一部分。 The x operator重複字符串n次。我們用它一次性替換@=的全部數量(注意+),重複的空字符串的次數與捕獲的字符串有字符次數相同。

如果您更喜歡沒有/e修飾符的解決方案,請繼續閱讀。

1 while $line =~ s/^(\s*)[@=]/$1 /; 

我們捕捉()零個或多個空白\s,也嚴絲合縫無論是@=之一,所有固定字符串^的開始。然後我們用來自()的捕獲$1和空白替換它。

我們運行此替換作爲while循環的條件,因爲我們希望它在每次嘗試後都重置正則表達式引擎的位置,因爲字符串的開頭已更改。該1 whilepost-fix syntax是寫作的只是一小段路:

while ($line =~ s/^(\s*)[@=]/$1 /) { 
    # do nothing 
} 

代碼的輸出,與上述相同的程序運行,是:

word <= Remove @ 
word <= Remove = 
    word <= Remove @ AND = 
    word <= Remove = AND @ 
      word <= Remove all the = and @ 

爲了說明爲什麼這是做什麼它做,試試這個:

while (my $line = <DATA>) { 
    print $line; 
    print $line while $line =~ s/^(\s*)[@=]/$1 /; 
} 

你會看到它是如何開始在與1 while ...循環的每個迭代。

@word <= Remove @ 
word <= Remove @ 
=word <= Remove = 
word <= Remove = 
@=word <= Remove @ AND = 
=word <= Remove @ AND = 
    word <= Remove @ AND = 
[email protected] <= Remove = AND @ 
@word <= Remove = AND @ 
    word <= Remove = AND @ 
[email protected][email protected][email protected][email protected]@word <= Remove all the = and @ 
@[email protected][email protected][email protected]@word <= Remove all the = and @ 
    [email protected][email protected][email protected]@word <= Remove all the = and @ 
    [email protected][email protected][email protected]@word <= Remove all the = and @ 
    @[email protected][email protected]@word <= Remove all the = and @ 
    [email protected][email protected]@word <= Remove all the = and @ 
     @[email protected]@word <= Remove all the = and @ 
     [email protected]@word <= Remove all the = and @ 
     @@word <= Remove all the = and @ 
     @word <= Remove all the = and @ 
      word <= Remove all the = and @ 
+1

'S/^([@ =] +)/」,「×長$ 1/e'得到的空間,避免了一段時間:) – Tanktalus

+0

@Tanktalus謝謝你,更新。 – simbabque

+0

我不知道爲什麼這是downvoted。也許TLDR? – simbabque

1

您可以通過代線開始(^)與@=[@=])做到這一點:

perl -lane 's/^[@=]//g; print ' file.txt