
BillKSmith
Veteran
Dec 19, 2012, 9:04 AM
Post #2 of 6
(3195 views)
|
Re: [joseph4325] Matching a string and printing a variable on the same line
[In reply to]
|
Can't Post
|
|
You really have not told us enough to help much. Let me make a few guesses. It seems as if you want to read some kind of a log file and display the time stamps of all entries which contain a specified message. I will assume that you specfy the message by including a key word or phrase on the command line. From your example, I assume that the log file contains nothing but valid entries. Each entry is on one line. Each entry consists of a time-stamp, a space, a hyphen, a space, and the message. Assuming that the log file is called "mylogfile.log", The following code shold get you started.
use strict; use warnings; my ($message_key) = @ARGV; open my $LOG_FILE, '<', "mylogfile.log" or die "cannot open log file: 0!"; while (my $entry = <$LOG_FILE>) { next if $entry !~ /$message_key/; $entry = s/^([^-]+)\s-\s.*/$1/; print $entry, "\n"; } Note: An entry is skipped if it does not contain the key. Otherwise, everything but the time-stamp is deleted, and the remainder of the entry (the time-stamp) is printed. Good Luck, Bill
|