2012-10-31 42 views
0

我正在做一個目錄清理來檢查我們的測試環境中沒有使用的文件。我有一個所有文件名的列表,這些文件名是按字母順序排列在一個文本文件中的,而另一個文件是我想要比較的。多列文件比較

這是第一個文件是如何設置:

test1.pl 
test2.pl 
test3.pl 

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

我想比較的文件是一個選項卡文件,它列出了每臺服務器作爲測試運行的腳本,並且顯然存在許多重複項。我想從這個文件中刪除測試腳本名稱,並將其與另一個文件進行比較,使用uniqsort,以便我可以用diff這個文件來查看哪些測試腳本沒有被使用。

該文件是設置爲這樣:

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

有一些線具有較少和一些具有更多。我的第一個衝動是製作一個Perl腳本來分割線條,並將它們推入列表中,如果它們不在那裏,但看起來完全沒有效率。我不是經驗awk,但我認爲有不止一種方法來做到這一點。任何其他想法來比較這些文件?

+0

聽起來像'comm'的工作,但您需要先進行一些預處理,以便每行列出一個文件名,而不是當前的格式。但是一旦你有兩個文件列表,'comm'可以告訴你哪一行在列表中,或者兩者都有。 – twalberg

+0

@twalberg我可以很容易'剪掉'非腳本列。你的意思是將文件名分割到各自的行嗎?那麼我會使用'uniq'。儘管你有我的想法。 – squiguy

+2

我無法弄清楚你正在嘗試做什麼。我們沒有長時間告訴我們爲什麼你創建了一個文件,只需向我們展示你想要比較的2個文件(如果這就是你正在做的),你想從比較中得到的輸出以及爲什麼那將是預期的產出。 –

回答

1

一個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 
0

快速而骯髒的腳本來完成這項工作。如果聽起來不錯,請使用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"; 
     } 
    } 

}

0

如果我正確理解你的需要你有一個測試的列表(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將其與原始文件進行比較。

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

1

通過awk重新排列文件名爲第二個文件中每行一個,然後diff與第一個文件的輸出。正在使用的服務器

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

很難說,因爲您沒有發佈預期的輸出,但這是您要找的?

$ 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 
+0

沒有真正具體的輸出我想要的。但是,你所擁有的是正確的。 – squiguy