我如何使用Perl对文本文件进行grep和排序? [英] How can I grep and sort text files using Perl?

查看:430
本文介绍了我如何使用Perl对文本文件进行grep和排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常混乱的简单日志文件,我需要它很整洁。该文件包含日志标题,但它们都混杂在一起。因此我需要根据日志标题对日志文件进行排序。没有静态数量的行 - 这意味着文本文件的每个标题没有固定数量的行。我使用perl grep来分类标题。



日志文件如下所示:

  Car LogFile标题
< text>
< text>
< text>
Car LogFile标题
< text>
Car LogFile标题
<等等>

我已经完成/搜索了一个简单的算法,但它似乎没有工作。有人能指导我吗?谢谢!

 #!/ usr / bin / perl 

#use 5.010; #必须存在才能导入新的5.10函数,请注意
#它是5.010而不是5.10


my $ srce =./root/Desktop/logs/Default。登录;
my $ string1 =Car LogFile Header;
打开(FH,$ srce);
my @buf =< FH>;
关闭(FH);
my @lines = grep(/ $ string1 /,@buffer);

执行代码后,终端上不显示结果。任何想法?

解决方案

我想你想要的东西像:

  my $ srce =./root/Desktop/logs/Default.log; 
my $ string1 =Car LogFile Header;

打开我的$ fh,'<',$ srce或死无法打开$ srce:$!;

my @lines = sort grep / \ Q $ string1 /,< $ fh>;
print @lines;

确保您有正确的文件路径,并且文件的行符合您的测试模式。 / p>

好像你错过了很多非常基本的概念,可能会剪切和粘贴你在其他地方看到的代码。如果您刚开始,请选择一个Perl教程,例如学习Perl perlfaq2 中列出了其他书籍和参考资料。


I have a simple log file which is very messy and I need it to be neat. The file contains log headers, but they are all jumbled up together. Therefore I need to sort the log files according to the log headers. There are no static number of lines - that means that there is no fixed number of lines for the each header of the text file. And I am using perl grep to sort out the headers.

The Log files goes something like this:

Car LogFile Header
<text>
<text>
<text>
Car LogFile Header
<text>
Car LogFile Header
<and so forth>

I have done up/searched a simple algorithm but it does not seem to be working. Can someone please guide me? Thanks!

#!/usr/bin/perl

#use 5.010; # must be present to import the new 5.10 functions, notice 
#that it is 5.010 not 5.10


my $srce = "./root/Desktop/logs/Default.log";
my $string1 = "Car LogFile Header";
open(FH, $srce);
my @buf = <FH>;
close(FH);
my @lines = grep (/$string1/, @buffer);

After executing the code, there is no result shown at the terminal. Any ideas?

解决方案

I think you want something like:

 my $srce = "./root/Desktop/logs/Default.log";
 my $string1 = "Car LogFile Header";

 open my $fh, '<',  $srce or die "Could not open $srce: $!";

 my @lines = sort grep /\Q$string1/, <$fh>;
 print @lines;

Make sure you have the right file path and that the file has lines that match your test pattern.

It seems like you are missing a lot of very basic concepts and maybe cutting and paste code you see elsewhere. If you're just starting out, pick up a Perl tutorial such as Learning Perl. There are other books and references listed in perlfaq2.

这篇关于我如何使用Perl对文本文件进行grep和排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆