Re: Find a line in a text file then print a field
- From: "nobull67@xxxxxxxxx" <nobull67@xxxxxxxxx>
- Date: 14 Nov 2006 16:20:03 -0800
prichard@xxxxxxx wrote:
Background: My employer is moving our backup software and robots from
*nix to Windows. I had written a crude ksh script that grep'ed a line
from a text file and then awk'ed a field from that line. The field is
the name of a backup tape. Now I need to use something other than ksh
to do the same thing on Windows and perl seems like the right way to
go.
The text file:
Try 1
PROCESS 1159229039 3864 bptm
PROCESS 1159229039 1088 bpbrm
CONNECT 1159229039
CONNECTED 1159229039
MOUNTING 1159229044 FFU458
MOUNTED 1159229083 FFU458
POSITIONING 1159229089 FFU458 9
POSITIONED 1159229204 FFU458
BEGIN_WRITING 1159229204
END_WRITING 1159229324
Started 1159229028
KbPerSec 2437
Kilobytes 288690
Files 536
ActivePid 1724
RqstPid 2476
MainPid 2372
Status 0
DestStorageUnit ilmmtms3fp1_robot2
DestMediaServer ilmmtms3fp1
NumTapesToEject 1088
Ended 1159229333
I need to "grep" the line with the word "POSITIONING" in it and "awk"
out the 4th field, in this case FFU458. I used perl's grep to get the
right line but after much futzing with functions like split, gw and
others I can't get the 4th field.
(split)[3]
Here is "grep" part of my perl script so far (ommitting the various
iterations of split,substr and gw that don't work):
--------snip------------------
open INPUT, "539.t";
open OUTPUT, "plr";
It is confusing to have an input file handle called OUTPUT.
Did you perhaps mean to open plr for output? If not you really should
think of a better name.
Note the old bareword global filehandles used in Perl4 are better
avoided most of the time in Perl5. As is the old two parameter open in
which the filename an mode are merged into a single argument. Perl does
not throw an execption if open() fails it simply sets the special
variable $! and returns false. To convert this into an exception you
need to die().
open my $input, '<', "539.t" or die $!;
open my $output , '>' , "plr" or die $!;
while ( <INPUT> ) {
chomp;
@TAPENAME = grep /POSITIONING/, ($_);
print @TAPENAME;
}
Ok, there a significant number of misconceptions.
The perl grep function loops over list of strings you pass it.
You are calling grep _within_ a loop processing one line at a time. You
do not want two nested loops.
You should get rid of one or other and say something like...
while ( <$input> ) {
if (/POSITIONING/) {
print ((spilt)[3]);
}
}
....or...
my @lines = grep /POSITIONING/, <$input>;
# Do whatever with lines
.
- References:
- Find a line in a text file then print a field
- From: prichard@xxxxxxx
- Find a line in a text file then print a field
- Prev by Date: Re: Perl - Bit Manipulation
- Next by Date: Re: Find a line in a text file then print a field
- Previous by thread: Find a line in a text file then print a field
- Next by thread: Re: Find a line in a text file then print a field
- Index(es):
Relevant Pages
|