2012-05-28 67 views
2

我試圖掃描包含特定字符串的行的文件,並將行打印到另一個文件。Bash/perl從文件打印行,直到出現條件的字符

但是,我需要打印出多行,直到「)」字符如果包含字符串的行以「,」結尾,則忽略空格。

目前我使用

for func in $fnnames 
do 
    sed/"$func"/p <$file >>$CODEBASEDIR/function_signature -n 
done 

其中$ FUNC包含字符串我期待已久,但當然不會爲限制工作。

有沒有辦法做到這一點?目前使用bash,但perl也很好。 謝謝。

+0

顯示一些示例輸入和預期輸出。 – TLP

回答

0

你的問題很棘手,因爲你的限制並不精確。你說 - 我認爲 - 一個塊應該是這樣的:

foo, 
bar, 
baz) 

哪裏foo是啓動塊,和關閉括號結束它的字符串。但是,你也可以說:

foo bar baz) xxxxxxxxxxx, 

你只想打印,直到),這是說foo bar baz),如果符合逗號結尾。

你可以可以說,只有以逗號結尾的行應繼續:

foo, # print + is continued 
bar # print + is not continued 
xxxxx # ignored line 
foo # print + is not continued 
foo, 
bar, 
baz) # closing parens also end block 

因爲我只能猜測你的意思是第一選擇,我給你兩個選擇:

use strict; 
use warnings; 

sub flip { 
    while (<DATA>) { 
     print if /^foo/ .. /\)\s*$/; 
    } 
} 

sub ifchain { 
    my ($foo, $print); 
    while (<DATA>) { 
     if (/^foo/) { 
      $foo = 1;   # start block 
      print; 
     } elsif ($foo) { 
      if (/,\s*$/) { 
       print; 
      } elsif (/\)\s*$/) { 
       $foo = 0;  # end block 
       print; 
      } 
      # for catching input errors: 
      else { chomp; warn "Mismatched line '$_'" } 
     } 
    } 
} 


__DATA__ 
foo1, 
bar, 
baz) 
sadsdasdasdasd, 
asda 
adaffssd 
foo2, 
two,  
three) 
yada 

第一個將打印從以foo開始的行與以)結尾的行之間找到的任何行。它會忽略「以逗號結束的行」限制。在積極的方面,它可以被簡化爲一個班輪:

perl -ne 'print if /^foo/ .. /\)\s*$/' file.txt 

第二個是隻是一個簡單的,如果結構,這將考慮這兩種限制,並警告(打印到STDERR),如果它發現一個線在兩個不匹配的塊內。

+0

抱歉不清楚,但是,我的意思是第一個案件。 – Kii

0
perl -ne 'print if 1 .. /\).*,\s*$/'