Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5272578
  • 博文数量: 1144
  • 博客积分: 11974
  • 博客等级: 上将
  • 技术积分: 12312
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-13 20:06
文章存档

2017年(2)

2016年(14)

2015年(10)

2014年(28)

2013年(23)

2012年(29)

2011年(53)

2010年(86)

2009年(83)

2008年(43)

2007年(153)

2006年(575)

2005年(45)

分类: LINUX

2010-03-07 12:32:44

 am with no luck been trying to print all lines between two keywords that I have defined.

Not sure what the heck I am doing wrong.

I have a variable "$linesFromFile" which contains all data from a file.  If I print the $linesFromFile I get correct results.  Now what I am not getting results for is I am trying to print all lines between the two strings shown below, sometimes the (start and end) strings only appear once, sometimes many times.  What I am trying to do is print all lines for every time the two strings are found.

Not sure how to on match and save all lines between to search strings.  I tried the save () and print $1 with no luck also.   

Thanks for the help in advance.

CODE

for ( $linesFromFile ) {
    if ( /^StartTr1/gm .. /^oflTr1/gm ) {
        print;
    }
}

SAMPLE FILE

CODE

StartTr1
sample 1
sample 1
sample 1
sample 1
SAMPLE 1
oflTr1
nothing
nothing
nothing
StartTr1
sample 2
sample 2
sample 2
sample 2
sample 2
last line before sample 2
oflTr1
junk
junk
junk

RESULTS DESIRED
sample 1
sample 1
sample 1
sample 1
SAMPLE 1

sample 2
sample 2
sample 2
sample 2
sample 2
last line before sample 2
Check Out Our Whitepaper Library. .
(MIS)
9 Nov 09 18:38
The problem is that you have your entire file in one scalar variable, the for loop only executes once, for the entire contents of that variable.  You would do better to read the data into an array of lines rather than one scalar, e.g.

CODE

#!/usr/bin/perl -w
strict;

#local $/;      # slurp mode

@linesFromFile=;

for ( @linesFromFile ) {
    if ( /^StartTr1/ ... /^oflTr1/ ) {
        ;
    }
}

__DATA__
StartTr1
sample 1
sample 1
...

However, as you can see, the output of that includes the starting and finishing markers, which you don't want.  I'm not sure if there is a cleverer way to do it with range expressions, but I'd probably do something like this:

CODE

$printit=0;
for ( @linesFromFile ) {
    $printit=0 if /^oflTr1/;
     if $printit;
    $printit=1 if /^StartTr1/;
}

Annihilannic.

(Programmer)
10 Nov 09 2:36
Or...

CODE

for($linesFromFile){
  while(/^StartTr1(.+?)^oflTr1/gms){
    print$1;
  }
阅读(2393) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~