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

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

问题描述

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

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.

日志文件是这样的:

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?

推荐答案

我想你想要这样的:

 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.

您似乎遗漏了许多非常基本的概念,并且可能会剪切和粘贴您在别处看到的代码.如果您刚刚开始,请阅读 Perl 教程,例如学习 Perl.perlfaq2 中列出了其他书籍和参考资料.

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天全站免登陆