简体   繁体   English

如何在条件语句中省略grep输出

[英]how to omit grep output in conditional statement

On a Mac, I want to determine if there are any sleep assertions present, using pmset. 在Mac上,我想使用pmset确定是否存在任何睡眠断言。 If there are, extract only that information and omit unnecessary information. 如果存在,则仅提取该信息并忽略不必要的信息。

If grep returns nothing I want to print "Nothing". 如果grep不返回任何内容,我想打印“无”。

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

The problem is that the first grep result is printed, and so is the formatted one. 问题是第一个grep结果被打印了,格式化后的结果也被打印了。 For example this is what I get if a backup is in progress: 例如,如果正在进行备份,这就是我得到的:

sleep 15 (sleep prevented by backupd) 睡眠15(通过备份避免睡眠)

sleep prevented by backupd 备份阻止睡眠

I don't want the first line, and want to discard it. 我不希望第一行,而是要丢弃它。 I only want the second line to print ("sleep prevented by backupd"). 我只希望打印第二行(“备份阻止睡眠”)。

If the grep result is empty I want to indicate that with the text "Nothing". 如果grep结果为空,我想用“ Nothing”文本表示。 The above script works OK for that. 上面的脚本可以正常运行。

There are probably many more elegant solutions but I've been searching days for one. 可能还有许多更优雅的解决方案,但我一直在寻找一种解决方案。

If i understand your question properly, you simply need to discard the output of first grep irrespective of the output it provides. 如果我正确理解了您的问题,则只需丢弃first grep的输出,而不管它提供的输出是什么。 If it's so, then you can use -q option provided by grep. 如果是这样,则可以使用grep提供的-q选项。

From the man page for 'grep': 在“ 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.)

Something like this: 像这样:

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


Obviously in the above example, output of ifconfig will not change every time. 显然,在上面的示例中,ifconfig的输出不会每次都更改。 Just used as an example. 仅用作示例。 ;) ;)

Redirect the output to /dev/null : 将输出重定向到/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

This is maybe a little more succinct. 这也许更简洁。 It gets grep to only output the part of the line that matches the pattern instead of the whole line, by using grep -o : 通过使用grep -o ,它使grep只输出与模式匹配的那部分而不是整个行:

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

The pattern is sleep prevented and any characters following until a ) is encountered. 该模式是sleep prevented和下面的任何字符,直至)遇到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM