2014-02-27 26 views
1

我需要檢查,如果一個變量某處的文件中找到(匹配從開始到結束的確切線),例如:什麼是最簡單的方法來檢查一個變量是否與BASH中某個文件內某行匹配?

if [ "$find" is in file.txt ] 
then 
    echo "Found." 
else 
    echo "Not found." 
fi 

我一直在使用grep -c '^$find$' > count.txt,然後count="$(cat count.txt)",然後檢查是否$count是大於「0」,但這種方法似乎效率低下。

什麼是最簡單的方法來檢查,如果一個變量被發現,完全,作爲一個文件中的某一行?

回答

5

使用grep

grep -q "$find" file.txt && echo "Found." || echo "Not found." 

如果你想整行匹配,使用-x選項:

grep -xq "$find" file.txt && echo "Found." || echo "Not found." 

報價man grep

-q, --quiet, --silent 
      Quiet; do not write anything to standard output. Exit immedi- 
      ately with zero status if any match is found, even if an error 
      was detected. Also see the -s or --no-messages option. 

    -x, --line-regexp 
      Select only those matches that exactly match the whole line. 

以上內容也可以寫成:

if grep -xq "$find" file.txt; then 
    echo "Found." 
else 
    echo "Not found." 
fi 
+0

您需要錨'^和$'來匹配整行。 – anubhava

+1

@anubhava對於'grep'提供'-x'選項。 – devnull

+0

是的'-x'也很好,以避免錨點。 +1 – anubhava

相關問題