简体   繁体   English

Perl脚本比较两个文件,但按顺序打印

[英]Perl script to compare two files but print in order

I have followed this question perl compare two file and print the matching lines and found lines which match or dont match between two files using hash. 我遵循了这个问题, Perl比较了两个文件并打印了匹配的行,并找到了使用哈希在两个文件之间匹配或不匹配的行。

But I find that hash rearranges the lines and I want the lines in order. 但是我发现哈希值重新排列了行,并且我希望行按顺序排列。 I can write multiple for loops to get results in order but this is not as efficient as hash. 我可以编写多个for循环来按顺序获取结果,但这不如哈希有效。 Has anyone faced this issue before and could please help with their solution 有没有人以前遇到过这个问题,请帮助他们解决问题

Maybe don't understand fully the question but 也许不完全理解这个问题,但是

fgrep -xf file2 file1

is not enough? 是不足够的?

or 要么

fgrep -xf file1 file2

yes, it is not perl but, short simple and fast... 是的,它不是perl但是,简短而又快速...

This can be done efficiently in two steps. 这可以通过两个步骤有效地完成。 Let's assume you have been able to find the "lines that match" but they are in the wrong order; 假设您已经能够找到“匹配的线”,但是它们的顺序错误; then a simple grep can re-organize them. 那么一个简单的grep就可以重新组织它们。 Assuming you have a script matchThem that takes two inputs ( file1 and file2 ) and outputs them to tempFile , then the over all script will be: 假设您有一个脚本matchThem ,它接受两个输入( file1file2 )并将它们输出到tempFile ,那么整个脚本将是:

matchThem file1 file2 > tempFile
grep -Fx -f tempFile file1

The -Fx flag means: -Fx标志的意思是:

-F : find exact match only (much faster than wildcards)
-x : only match whole lines

如果要保留插入顺序的哈希,请尝试使用CPAN模块Tie :: IxHash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM