I would like to remove contents of a file from a certain character to a certain character in the file in Perl. How do I do that using a script?
The file has this:
Syslog logging: enabled (11 messages dropped, 2 messages rate-limited,
0 flushes, 0 overruns, xml disabled, filtering disabled)
Console logging: level informational, 81 messages logged, xml disabled,
filtering disabled
Monitor logging: level debugging, 0 messages logged, xml disabled,
filtering disabled
Buffer logging: level informational, 28 messages logged, xml disabled,
filtering disabled
Logging Exception size (4096 bytes)
Count and timestamp logging messages: disabled
No active filter modules.
Trap logging: level informational, 83 message lines logged
Log Buffer (4096 bytes):
*Oct 4 13:42:03.210: %SEC_LOGIN-5-LOGIN_SUCCE开发者_C百科SS: Login Success [user: ] [Source: ] [localport: ] at UTC Mon Oct 4 2010
And the new file after the trimming should be this
*Oct 4 13:42:03.210: %SEC_LOGIN-5-LOGIN_SUCCESS: Login Success [user: ] [Source: ] [localport: ] at UTC Mon Oct 4 2010
You don't give anywhere near enough information. But it sounds like something that can be done from the command line. Your solution will probably look something like this:
$ perl -ne 'print unless /start_skip/ .. /end_skip/' in.txt > out.txt
Update: Having seen your expanded explanation, it looks like you only want lines that start with an asterisk.
$ perl -ne 'print if /^\*/' in.txt > out.txt
If i well understand your needs, you can do something like :
I've updated according to your new specifications
#!/usr/bin/perl
use strict;
use warnings;
my $in_file = 'foo.txt';
my $out_file = 'bar.txt';
open my $fh_in, '<', $in_file or die "unable to open '$in_file' for reading: $!";
open my $fh_out, '>', $out_file or die "unable to open '$out_file' for writing: $!";
while(<$fh_in>) {
chomp;
# updated according to new requirements
next if (/^Syslog logging/ .. /^Log Buffer/);
next if (/^$/);
print $fh_out $_,"\n";
}
close $fh_in;
close $fh_out;
This script reads the file foo.txt
and write lines into file bar.txt
except those between begin_skip
and end_skip
included.
begin_kip
and end_skip
can be any regex.
Hmm, the question is not very clear. I guess you want to delete certain strings in a file.
#!/usr/bin/perl
$filename = $ARGV[0];
$a = $ARGV[1];
$b = $ARGV[2];
open (FILE, $filename) || die ("Can't open the file");
open (INFILE, ">$filename.tmp") || die ("Can't open the temp file");
while ($line = <FILE>) {
$line =~ s/$a.*$b/$a$b/g;
print INFILE $line
}
close (INFILE);
close (FILE);
I guess what you are expecting is in here "$line =~ s/$a.*$b/$a$b/g;" It only replaces the content between the string but not the actual string. You could simply call sed script
sed 's/a.*b/ab/g' file
精彩评论