2014-06-29 27 views
0

我想要一個bash腳本,將採取File1中的項目1,遍歷File2中的所有行和輸出,如果存在匹配。以遞歸方式繼續該模式,Item2,File1遍歷File2中的所有行進行匹配,繼續此模式,直至處理完文件1中的所有行。Bash Scipt比較兩個文件的匹配

現在,檢查這一點,樣本數據。

File1中 - 主機名的單柱,使用短名稱

 
vsie1p990 
vsie1p991 
vsie1p992 
... 

文件2 - 多列,逗號分隔,第一列是主機名(短名稱)

格式:短名稱,IP地址,FQDN

 
vsie1p992,191.167.44.212,vsie1p992.srv.us.company.com 

我嘗試以下,但有些事是不完全正確:

#!/bin/bash 
echo "Report Generated" 
date 

count=0 

while read list ; do 
{ 
    IT=`grep -i "$list" $2` 
    If [ -n "$IT" ] ; then 
    echo "Match Found: $list" 
    count=`expr "$count" + 1` 
    fi 
} 
done <$1 
echo "Total Matches = $count" 

運行示例:> ./checkit.sh列表1列表2

任何幫助,諮詢,指導,將不勝感激。

- 理查德

+0

您請求的模式非常低效。爲什麼你想要遵循這個算法? –

+3

...要清楚,你可以使用'join'來實現更好/更快的事情。 –

+0

結果有什麼問題?腳本不包括所有匹配嗎?您是否確定線條不會以空格或製表符或甚至CR-LF結尾,這會導致CR,空間等存在,從而減少甚至消除所有可能的匹配? –

回答

-1

我知道你問一個猛砸解決方案,但這個Python代碼要快很多。不是在第一個文件中的每一行對整個第二個文件運行一次grep,而是在第一個文件中讀取第一個文件,然後匹配第二個文件中的行。

import sys 

if len(sys.argv) != 3: 
    print("Usage: match_fnames <file_with_names> <log_file>") 
    sys.exit(1) 

file_with_names, log_file = sys.argv[1:] 

with open(file_with_names, "rt") as f: 
    set_of_names = set(line.strip() for line in f) 

total_matches = 0 
with open(log_file, "rt") as f: 
    for line in f: 
     fields = line.split(',') 
     hostname = fields[0] 
     if hostname in set_of_names: 
      total_matches += 1 
      sys.stdout.write(line) 

print("Total matches: {}".format(total_matches)) 

在一個名爲match_files.py文件,將這個,然後用運行它:`蟒蛇match_files.py filenames.txt LOGFILE.TXT」

這也將與Python 3.x的

運行得很好
2

你可以通過File1grep作爲模式列表:

grep -i -f File1 File2 > result 
echo -n "Total matches: "; wc --lines result | cut -d' ' -f1 
0

這可能是從效率的角度更好的閱讀所有的F ile_1將值搜索到bash中的數組,然後使用grep來測試file2中是否存在file_2中的代碼。這裏有一個例子:

#!/bin/bash 

# validation checks omitted 

declare -a codes 

code=(`<"$1"`) # read file1 values into array 
szcode=${#code[@]} # get the number of values read 

for ((i=0; i<$szcode; i++)); do 

    if `grep -q "${code[$i]}" "$2" &>/dev/null`; then 
     echo " [checking $i of $szcode codes] - ${code[$i]} found in $2" 
    fi 

done 

exit 0 

輸出:

[checking 1 of 3 codes] - vsie1p991 found in readtitle.sh 

這也讓在你得到什麼樣的信息可以從grep後面具有很大的靈活性。例如,它可能會返回匹配的行號等。