簡體   English   中英

與多列進行文件比較

[英]File comparison with multiple columns

我正在進行目錄清理以檢查我們的測試環境中沒有使用的文件。 我有一個列表,列出了在文本文件中按字母順序排序的所有文件名,以及我要比較的另一個文件。

以下是第一個文件的設置方式:

test1.pl
test2.pl
test3.pl

它是一個簡單的,每行文本文件的一個腳本名稱,我想根據下面的其他文件清理目錄中的所有腳本。

我要比較的文件是一個選項卡文件,它列出了每個服務器作為測試運行的腳本,顯然有很多重復項。 我想從這個文件中刪除測試腳本名稱並比較吐出到另一個文件,使用uniqsort以便我可以使用上面的文件來diff這個文件以查看哪些測試腳本沒有被使用。

該文件設置如下:

server: : test1.pl test2.pl test3.pl test4.sh test5.sh

有些線路較少,部分線路較多。 我的第一個沖動是制作一個Perl腳本來分割線並將值推入列表中,如果它們不在那里但是看起來完全沒有效率。 我不是在awk經歷過,但我認為有不止一種方法可以做到這一點。 還有其他想法來比較這些文件嗎?

這通過awk將文件名重新排列為第二個文件中的每行一個,然后將輸出與第一個文件區diff

diff file1 <(awk '{ for (i=3; i<=NF; i++) print $i }' file2 | sort -u)

Perl解決方案,它對服務器使用的文件進行%needed哈希,然后檢查包含所有文件名的文件。

#!/usr/bin/perl
use strict;
use warnings;
use Inline::Files;

my %needed;
while (<SERVTEST>) {
    chomp;
    my (undef, @files) = split /\t/;
    @needed{ @files } = (1) x @files;
}

while (<TESTFILES>) {
    chomp;
    if (not $needed{$_}) {
        print "Not needed: $_\n";   
    }
}

__TESTFILES__
test1.pl
test2.pl
test3.pl
test4.pl
test5.pl
__SERVTEST__
server1::   test1.pl    test3.pl
server2::   test2.pl    test3.pl
__END__
*** prints

C:\Old_Data\perlp>perl t7.pl
Not needed: test4.pl
Not needed: test5.pl

快速而骯臟的腳本來完成這項工作。 如果聽起來不錯,請使用open來通過正確的錯誤檢查來讀取文件。

use strict;
use warnings;
my @server_lines = `cat server_file`;chomp(@server_lines);
my @test_file_lines = `cat test_file_lines`;chomp(@test_file_lines);
foreach my $server_line (@server_lines){
   $server_line =~ s!server: : !!is;
   my @files_to_check = split(/\s+/is, $server_line);
   foreach my $file_to_check (@files_to_check){
      my @found = grep { /$file_to_check/ } @test_file_lines;
      if (scalar(@found)==0){
        print "$file_to_check is not found in $server_line\n";
      }
   }

}

如果我正確理解您的需要,您將擁有一個包含測試列表的文件(testfiles.txt):

test1.pl
test2.pl 
test3.pl
test4.pl
test5.pl

還有一個包含服務器列表的文件,其中包含所有測試的文件(serverlist.txt):

server1:        :       test1.pl        test3.pl
server2:        :       test2.pl        test3.pl

(我把所有空格都當作標簽)。

如果將第二個文件轉換為測試文件列表,則可以使用diff將其與原始文件進行diff

cut -d: -f3 serverlist.txt | sed -e 's/^\t//g' | tr '\t' '\n' | sort -u > tested_files.txt

cut刪除了服務器名稱和':', sed刪除了留下的前導標簽, tr然后將剩余的標簽轉換為換行符,然后我們進行獨特的排序以排序和刪除重復項。 這是輸出到tested_files.txt

然后你所做的就是diff testfiles.txt tested_files.txt

很難說,因為你沒有發布預期的輸出,但這是你想要的嗎?

$ cat file1
test1.pl
test2.pl
test3.pl
$
$ cat file2
server: : test1.pl test2.pl test3.pl test4.sh test5.sh
$
$ gawk -v RS='[[:space:]]+' 'NR==FNR{f[$0]++;next} FNR>2 && !f[$0]' file1 file2
test4.sh
test5.sh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM