2015-02-11 104 views
0

我是awk的新手,需要比較兩個文件的行數。 該腳本將返回true,如何比較使用awk的兩個文件的行數

if lines(f1) == (lines(f2)+1) 

否則爲false。我怎樣才能做到這一點?

問候

+2

什麼你試過嗎? – 2015-02-11 10:43:24

+1

通常情況下你會使用'wc -l'來計算文件中的行數......如果沒有,請看看Ed的答案,看看如何處理2個文件http://stackoverflow.com/questions/21280959/using -awk-to-process-two-different-files-consecutively – 2015-02-11 10:51:44

回答

2

如果它必須是awk

awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' file1 file2 

的varibale x遞增,幷包含file1線的數量和FNR包含file2數量。最後,兩者進行比較和腳本退出0或1

看到一個例子:

[email protected]:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' shortfile longfile 
[email protected]:~$ echo $? 
1 
[email protected]:~$ awk 'NR==FNR{x++} END{ if(x!=FNR){exit 1} }' samefile samefile 
[email protected]:~$ echo $? 
0 
+0

:-)非常簡潔 - 有投票權。實際上,'awk'自然會退出狀態爲零,所以如果你反轉邏輯並退出狀態1,你可以省略'exit 0'。 – 2015-02-11 13:07:13

+0

@MarkSetchell啊,謝謝goot point – chaos 2015-02-11 13:09:41

+0

你甚至可以做'END {exit(x!= FNR)}'但也許這太混亂了。 – 2015-02-11 21:07:14

0

像這樣的東西應該根據自己的意圖:

[ oele3110 $] cat line_compare.awk 
#!/usr/bin/gawk -f 

NR==FNR{ 
    n_file1++; 
} 
NR!=FNR{ 
    n_file2++; 
} 

END{ 
    n_file2++; 
    if(n_file1==n_file2){exit(1);} 
} 
[ oele3110 $] cat f1 
1 
1 
1 
1 
1 
1 
[ oele3110 $] cat f2 
1 
1 
1 
1 
1 
[ oele3110 $] cat f3 
1 
1 
1 
1 
1 
[ oele3110 $] 
[ oele3110 $] wc -l f* 
6 f1 
5 f2 
5 f3 
16 total 
[ oele3110 $] ./line_compare.awk f1 f2 
[ oele3110 $] echo $? 
1 
[ oele3110 $] ./line_compare.awk f2 f3 
[ oele3110 $] echo $? 
0 
[ oele3110 $] 

其實,我覺得我應該問你給你答案之前投入更多的精力。我現在就離開它,但下次我不會犯同樣的錯誤。