2017-02-21 30 views
2

我想提出一個劇本,我的學校,我不知道我怎麼會檢查文件,如果該字符串不是在文件中,做一個代碼,但如果是繼續,就像這樣:雖然文件不包含字符串BASH

while [ -z $(cat File.txt | grep "string") ] #Checking if file doesn't contain string 
do 
    echo "No matching string!, trying again" #If it doesn't, run this code 
done 
echo "String matched!" #If it does, run this code 
+1

所以...你有什麼問題 –

回答

4

你可以這樣做:

$ if grep "string" file;then echo "found";else echo "not found" 

爲了做一個循環:

$ while ! grep "no" file;do echo "not found";sleep 2;done 
$ echo "found" 

但要小心不要進入一個無限循環。字符串或文件必須改變,否則循環沒有意義。

以上,如果/當基於命令的返回狀態,而不是結果的作品。 如果grep發現文件中的字符串將返回0 =成功= true 如果grep找不到字符串將返回1 =不成功= false

通過使用!我們將「false」恢復爲「true」以保持循環運行,因爲儘管循環處於某種狀態。

一個更傳統的while循環將類似於你的代碼,但沒有無用的使用貓和額外的管道:

$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done 
$ echo "found" 
+0

這就是我想,但我?希望它繼續打印「找不到」,直到找到字符串。 –

+0

@Python更新 –

+0

@Python更新和解釋。是你在找什麼...? –

2

如果測試語句是否「串」不file.txt簡單:

#!/bin/bash 
if ! grep -q string file.txt; then 
    echo "string not found in file!" 
else 
    echo "string found in file!" 
fi 

-q選項(--quiet--silent)確保輸出不被寫入到標準輸出。

一個簡單的while循環測試是一個「串」不file.txt

#!/bin/bash 
while ! grep -q string file.txt; do 
    echo "string not found in file!" 
done 
echo "string found in file!" 

注:知道的可能性while循環可能會導致死循環!

+0

@與我的解決方案有什麼不同? –

+1

如果找不到'grep'的'-q'選項,字符串將被打印到標準輸出。 –

0

另一種簡單的方法是隻做到以下幾點:

[[ -z $(grep string file.file) ]] && echo "not found" || echo "found" 

&&手段和 - 或執行下面的命令,如果以前是真正

||手段或 - 或執行,如果前面的是

[[ -z $(expansion) ]]手段返回如果擴展輸出爲

此行是很像一個雙重否定,基本上是: 「返回如果字符串不在文件中找到。文件;然後回顯沒有找到如果,或發現如果

例子:

bashPrompt:$ [[ -z $(grep stackOverflow scsi_reservations.sh) ]] && echo "not found" || echo "found" 
not found 
bashPrompt:$ [[ -z $(grep reservations scsi_reservations.sh) ]] && echo "not found" || echo "found" 
found