孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

假如有一个从WEB上拷贝下来的文件

01 #!/usr/bin/perl -w 

02   

03 use Tk; 

04   

05 $Tk::strictMotif = 1; 

06   

07 $main = MainWindow->new(); 

08   

09 $button1 = $main->Button(-text => "Exit", 

10                          -command => \&exit_button, 

11                          -foreground => "orangered" ); 

12   

13 $button1->pack(); 

14 $button1->configure(-background => "white" ); 

15 $button2 = $main->Button(-text => "Push Me", 

16                          -command => \&change_color, 

17                          -foreground => "black",  

18                          -background => "steelblue"); 

19   

20 $button2->pack(); 

21   

22 MainLoop(); 

23   

24 sub exit_button { 

25     print "You pushed the button!\n"; 

26     exit; 

27 } 

28   

29 sub change_color { 

30     $button1->configure(-background => "red", 

31                         -foreground => "white"); 

32     $button2->configure(-background => "maroon", 

33                         -foreground => "white", 

34                         -font       => "-*-times-bold-r-normal-20-140-*"); 

35 }

现在想去掉其中的前导数字和空格,可用以下代码解决(打印在屏幕上)

use strict;
use warnings;

my $file="./s1";

if (! open (FILE,"$file")) {
    die "can not open file"
}

while (<FILE>) {
  chomp;
  if (/^(\d+\s+)(\S+)/) {   #如果存在前导数字和空格并且不是空代码行,去掉此句将保留空行
    s/^(\d+\s+)//;           #替换前导数字和空格
    print "$_\n";
  }
}

当然可以直接修改文件,将修改的结果直接存回原文件,即修改原文件,可以用open文件操作,如下:

use strict;
use warnings;

my $tmp;
my $file="./s1";
my $buffer="./tmp.txt";
open F,"$file" or die $!;
open T,">>$buffer" or die $!;
$^I=".bak";   #空时,则不备份

while ($_=readline F) {
  if (defined $_) {
    chomp;
    if (/^(\d+\s+)(\S+)/) {
       s/^(\d+\s+)//;
       $tmp=$tmp . "$_\n";
    }
  }
}
print $tmp;
print T $tmp;
close T;
close F;
rename ("$buffer","$file") or die ("file in use!");

用sed更简洁

sed -i 's/^[0-9]*[ ]*//' s2.txt

sed '/^[[:space:]]*$/d' s2.txt     #删除全部空行

posted on 2011-05-12 20:06  孤独的猫  阅读(225)  评论(0编辑  收藏  举报