2016-02-25 46 views
1

我想報告使用grep和while找到的行。雖然閱讀grep線

我知道你可以使用下面的目標文件來比較inputs.txt字符串列表,找到他們,像這樣:

grep -f inputs.txt file_to_check 

我想是讀該字符串的每一行並循環grep他們個人。

所以我曾嘗試以下方法:

cat inputs.txt | while read line; do if grep "$line" filename_to_check; then echo "found"; else echo "not found"; fi; done 

當我將輸出重定向到一個文件,該返回什麼。

while read line 
do 
if grep "$line" file_to_check 
    then echo "found" 
else 
    echo "not found" 
fi 
done < inputs.txt 

與第一個相同,但從我發現的更好做。

我知道它逐行迭代,因爲我可以用echo $ line替換grep,並打印每行;但無論哪種方法不一樣的grep -f以上返回任何東西,相反,它表明:

not found 
not found 
not found 
. 
. etc. 

所以,我正在尋找的東西在那裏將通過每一行迭代和if語句使用grep的通過檢查以確定grep是否真的找到了它。我知道我可能不具備正確的邏輯,但爲我想應該是這個樣子的輸出:

Found *matching line in file_to_check* 
Found *matching line in file_to_check* 
Not Found $line *(string that does not match)* 
. 
. etc. 
+0

讀取測試命令或'[' – karakfa

回答

0

那麼,你的if語句是相當自由的形式,你可能需要一點對於bash清理,能夠閱讀它。例如:

if [ "$(grep "$line" file_to_check)" != "" ]; then 
    echo "found:  $line" 
else 
    echo "not found: $line" 
fi 

這個if語句會如果grep命令找到行評估真實的,因爲如果這樣做,會吐出線路輸出,並且將不等於「」,或空字符串。

+0

感謝,我發現文件中的特殊車廂返回的grep不知道如何處理。所以我通過VIM將內容複製到另一個測試文件中,並且報告了我想要的內容。 @Skyler,你的例子雖然有所幫助,但它給出了一些奇怪的輸出,甚至用我測試後生成的新文件進行測試。輸出使用: while read line;如果[$(grep「$ line」file_to_check)!=「」]做 ;然後 回聲 「發現:$行」 其他 回聲 「未找到:$行」 網絡 完成 Joshua

+0

我的歉意@Joshua,$(command)應該被雙引號括起來,回答更新。 – Skyler

+0

@Joshua如果文件包含回車符,使用'dos2unix'將其轉換爲普通的Unix換行符。 – Barmar

1

您還可以使用&&||運營商:

while read line; do 
     grep -q "$line" file_to_check && echo "$line found in file_to_check" || echo "$line not found in file_to_check" 
done <inputfile> result.txt 

上的grep的-q參數只是輸出狀態代碼:

  • 如果$line被發現,它outpouts 0(真)命令&&將被評估
  • 如果未找到,它會輸出1(False)afte命令[R ||將評估
0

這是我的最終解決方案:再次

file=$(dos2unix inputs.txt) 
new_file=$file 

while read line 
do 
    if [ "$(grep "$line" filename)" != "" ] 
    then echo "found: $line" 
    else echo "not found: $line" 
    fi 
done <$new_file 

謝謝!

+0

不要'if [「$(grep」$ line「filename)」!=「」]''。只要執行'if grep -q「$ line」filename「。 –

1

你可以重寫你的最終解決方案爲

# Do not need this thanks to tr: file=$(dos2unix inputs.txt) 

# Use -r so a line with backslashes will be showed like you want 
while read -r line 
do 
    # Not empty? Check with test -n 
    if [ -n "$(grep "${line}" filename)" ]; then 
     echo "found: ${line}" 
    else 
     echo "not found: ${line}" 
    fi 
done < <(tr -d "\r" < "${file}")