[英]Multiple "grep...then..." in bash
我正在编写一个 bash 脚本,它监视脚本 A 的 output,并通过“grep”命令匹配关键字。 如果成功找到关键字,请回显某些内容。 这是我的脚本:
if script_A | grep -q 'keyword';
then
echo 'Found A!'
如果只有一个条件,脚本 function 很好。 但是我找不到匹配多个关键字的方法,并使用“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!'
谢谢!
如果每次写入只能有一个读者消费。 然后,该读取器可以创建它读取的数据的多个副本(就像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
如果您很高兴看到 grep 的grep
(而不是您的自定义消息),您可以这样做:
if ! script_A | grep -e 'keyword_A' -e 'keyword_B'; then
echo 'Found Nothing'
fi
在管道中直接操作 grep 的 output 有点困难,但您可以通过以下方式获取自定义消息:
if ! script_A | grep -o -e 'keyword_A' -e 'keyword_B'; then
echo 'Nothing'
fi | sed -e 's/^/Found /' -e 's/$/!/'
您可以使用 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
万一有人需要,我找到了可行的答案:
#;/bin/bash function test() { echo "test" sum=0 while true do stat_date=`date` echo $stat_date done } function checkcondition() { while read data: do if [[ $data == *"10:52;59"* ]]; then echo "Found the time;"; elif [[ $data == *"hi"* ]]; then echo "Found hi;"; else echo "Nothing"; fi done; } test | checkcondition
代码将不断生成时间字符串。 并且检查条件 function 将收到 output。 每当 output 字符串包含“10:52:59”时,它将打印“找到时间”。 否则打印“无”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.