我想将文件的内容从某个字符中删除到Perl文件中的某个字符。如何使用脚本执行此操作?
该文件包含:
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_SUCCESS: Login Success [user: ] [Source: ] [localport: ] at UTC Mon Oct 4 2010
修剪后的新文件应为此
*Oct 4 13:42:03.210: %SEC_LOGIN-5-LOGIN_SUCCESS: Login Success [user: ] [Source: ] [localport: ] at UTC Mon Oct 4 2010
答案 0 :(得分:2)
您没有提供足够的信息。但这听起来像是可以从命令行完成的事情。您的解决方案可能看起来像这样:
$ perl -ne 'print unless /start_skip/ .. /end_skip/' in.txt > out.txt
更新:看过您的扩展说明后,您似乎只想要以星号开头的行。
$ perl -ne 'print if /^\*/' in.txt > out.txt
答案 1 :(得分:1)
如果我很了解您的需求,您可以执行以下操作:
我已根据您的新规格进行了更新
#!/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;
此脚本读取文件foo.txt
并将行写入文件bar.txt
,但begin_skip
和end_skip
之间的行除外。
begin_kip
和end_skip
可以是任何正则表达式。
答案 2 :(得分:0)
#!/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);
我猜你所期待的是“$ line = ~s / $ a。* $ b / $ a $ b / g;”它只替换字符串之间的内容,而不是实际的字符串。你可以简单地调用sed脚本
sed 's/a.*b/ab/g' file