我正在撰寫一個 bash 腳本,它監視腳本 A 的輸出,并通過“grep”命令匹配關鍵字。如果成功找到關鍵字,則回顯一些內容。這是我的腳本:
if script_A | grep -q 'keyword';
then
echo 'Found A!'
如果只有一個條件,腳本運行良好。但是我找不到匹配多個關鍵字的方法,并使用“if...elif...else”來控制不同條件下的回聲內容。
這是我試圖實作的邏輯:
script_A |
if grep 'keyword_A';
then echo 'Found A!'
elif grep 'keyword_B';
then echo 'Found B!'
else echo 'Found Nothing!'
謝謝!
uj5u.com熱心網友回復:
每次寫入只能有一個讀者消費 if。然后,該讀取器可以創建它讀取的資料的多個副本(就像這樣tee做),但最初在另一端必須只有一件事。
一種更傳統的方法是讓 shell 成為一個讀者,如下所示:
output=$(script_A)
if grep -q 'keyword_A' <<<"$output"; then
echo 'Found A!'
elif grep -q 'keyword_B' <<<"$output"; then
echo 'Found B!'
else
echo 'Found nothing!'
do
uj5u.com熱心網友回復:
如果您很高興看到grep(而不是自定義訊息)的輸出,則可以執行以下操作:
if ! script_A | grep -e 'keyword_A' -e 'keyword_B'; then
echo 'Found Nothing'
fi
在管道中直接操作 grep 的輸出有點困難,但是您可以通過以下方式獲得自定義訊息:
if ! script_A | grep -o -e 'keyword_A' -e 'keyword_B'; then
echo 'Nothing'
fi | sed -e 's/^/Found /' -e 's/$/!/'
uj5u.com熱心網友回復:
您可以使用 Bash 復賽:
if [[ "demo_rematch" =~ [st] ]]; then
echo "Matched from regexpr [st] is the letter ${BASH_REMATCH}!"
fi
使用單字母關鍵字,您可以執行以下操作
# grep [YES] is the same as grep [ESY]
for regex in '[AB]' '[YES]' '[NO]'; do
echo "$regex"
if [[ "$(printf "keyword_%s\n" {A..G})" =~ keyword_$regex ]]; then
echo "Found ${BASH_REMATCH/keyword_}!"
else
echo "Found Nothing!"
fi
done
在現實生活中,您的關鍵字可能會更復雜。您仍然可以使用相同的構造,但現在我不會使用字串“keyword_”。
regex='(foo|bar|A|B|not me|no match|bingo)'
echo "$regex"
for script_A in "String with foos" "String with bar" "String with A" "String with B" "Nothing here" "Please ignore me" "and bingo"; do
if [[ "${script_A}" =~ $regex ]]; then
echo "Found ${BASH_REMATCH}!"
else
echo "Found Nothing!"
fi
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398481.html
標籤:猛击
上一篇:'sed:noinputfiles'在回圈中使用sed-i時
下一篇:如何反轉日期格式
