簡體   English   中英

如何在條件語句中省略grep輸出

[英]how to omit grep output in conditional statement

在Mac上,我想使用pmset確定是否存在任何睡眠斷言。 如果存在,則僅提取該信息並忽略不必要的信息。

如果grep不返回任何內容,我想打印“無”。

if pmset -g | grep pre ; then pmset -g | grep pre | cut -d'(' -f2 | cut -d')' -f1 ; else printf "Nothing\n" ; fi

問題是第一個grep結果被打印了,格式化后的結果也被打印了。 例如,如果正在進行備份,這就是我得到的:

睡眠15(通過備份避免睡眠)

備份阻止睡眠

我不希望第一行,而是要丟棄它。 我只希望打印第二行(“備份阻止睡眠”)。

如果grep結果為空,我想用“ Nothing”文本表示。 上面的腳本可以正常運行。

可能還有許多更優雅的解決方案,但我一直在尋找一種解決方案。

如果我正確理解了您的問題,則只需丟棄first grep的輸出,而不管它提供的輸出是什么。 如果是這樣,則可以使用grep提供的-q選項。

在“ grep”的手冊頁中:

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

像這樣:

if ifconfig | grep -q X; then
        ifconfig | grep Mi | cut -d'(' -f2
else
        printf "Nothing\n"
fi


顯然,在上面的示例中,ifconfig的輸出不會每次都更改。 僅用作示例。 ;)

將輸出重定向到/dev/null

if pmset -g | grep pre >/dev/null 2>&1 ; then
    pmset -g | grep pre | cut -d'(' -f2 | cut -d')' -f1
else
    printf "Nothing\n"
fi

這也許更簡潔。 通過使用grep -o ,它使grep只輸出與模式匹配的那部分而不是整個行:

#!/bin/bash
SLEEP=$(pmset -g | grep -o "sleep prevented.*[^)]")
if [ -z "$SLEEP" ]; then
   echo Nothing
else
   echo $SLEEP
fi

該模式是sleep prevented和下面的任何字符,直至)遇到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM