2013-01-16 16 views
0

我有這個代碼塊工藝路線:擊:如果已經在第二個文件

while IFS=$'\n' read -r line || [[ -n "$line" ]]; do 
    if [ "$line" != "" ]; then 
     echo -e "$lanIP\t$line" >> /tmp/ipList; 
    fi 
done < "/tmp/includeList" 

我知道這一定是非常簡單的。但是我有另一個列表(/ tmp/excludeList)。我只想在我的while循環中回顯該行,如果該行不在我的excludeList中。我怎麼做。有一些awk語句或什麼?

+0

檢查內容:HTTP://theunixshell.blogspot.com/2012/12/file-comparisons-using-awk-match-columns.html – Vijay

回答

0

使用grep

while IFS=$'\n' read -r line || [[ -n "$line" ]]; do 
    if [[ -n ${line} ]] \ 
     && ! grep -xF "$line" excludefile &>/dev/null; then 
     echo -e "$lanIP\t$line" >> /tmp/ipList; 
    fi 
done < "/tmp/includeList" 

的-n $線意味着如果$行不爲空 如果$線被發現,排除這是由倒排文件上的grep返回true!如果找不到該行,則返回true。
-x表示匹配行,所以沒有其他行可以出現在行
-F表示固定字符串,所以如果任何元字符以$行結尾,他們將被字面匹配。

希望這有助於

+0

我認爲這是真的很接近。它似乎不工作,因爲我的includeList在最後一行的末尾沒有換行符,而我的excludeList也沒有。所以,基本上,我需要它不用擔心行尾是否有換行符。 – exvance

+0

嘗試在grep上開-x。 – peteches

+1

嘗試運行上面的awk或grep-only解決方案上的time命令,我期望你會發現這個速度至少要降低一個數量級。這是錯誤的方法。 –

3

你可以用grep單獨做到這一點:

$ cat file 
blue 
green 
red 
yellow 
pink 

$ cat exclude 
green 
pink 

$ grep -vx -f exclude file 
blue 
red 
yellow 

-v標誌告訴grep只輸出file行未在exclude發現-x標誌力量整行匹配。

+0

問題雖然是如果排除任何行不匹配行grep將返回true,所以不確定如果行不在文件中真正有用。 – peteches

+0

爲什麼退出狀態很重要,你只想在'file'中處理不在'exclude'中的行,所以'grep -vx -f exclude file | process..'? –

+0

啊,是啊,如果你在重定向到while循環之前用grep過濾。我正在考慮從循環內部清除排除文件。 – peteches

0

使用awk:

awk -v ip=$lanIP -v OFS="\t" ' 
    NR==FNR {exclude[$0]=1; next} 
    /[^[:space:]]/ && !($0 in exclude) {print ip, $0} 
' /tmp/excludeList /tmp/includeList > /tmpipList 

這讀取排除列表信息的陣列(如數組鍵) - 當AWK是從讀取參數的第一個文件NR==FNR條件爲真。然後,在讀取包含文件時,如果當前行包含非空格字符並且它不在排除數組中,請將其打印出來。

使用grep等效:

grep -vxF -f /tmp/excludeList /tmp/includeList | while IFS= read -r line; do 
    [[ -n "$line" ]] && printf "%s\t%s\n" "$ipList" "$line" 
done > /tmp/ipList 
相關問題