【问题标题】:How can I get the return value and matched line by grep in bash at once?如何在 bash 中一次通过 grep 获取返回值和匹配行?
【发布时间】:2017-03-31 20:10:21
【问题描述】:

我正在学习 bash。我想一次通过 grep 获取返回值和匹配行。

if cat 'file' | grep 'match_word'; then
  match_by_grep="$(cat 'file' | grep 'match_word')"
  read a b <<< "${match_by_grep}"
fi

在上面的代码中,我使用了两次 grep。我想不出一次如何通过 grep 来做到这一点。即使没有匹配的单词,我也不确定 match_by_grep 是否始终为空,因为 cat 可能会输出错误消息。

match_by_grep="$(cat 'file' | grep 'match_word')"
if [[ -n ${match_by_grep} ]]; then
  # match_by_grep may be an error message by cat.
  # So following a and b may have wrong value.
  read a b <<< "${match_by_grep}"
fi

请告诉我怎么做。非常感谢。

【问题讨论】:

  • 提供样本输入和预期输出
  • 显示输入,预期输出。
  • 附带说明,最好使用grep pattern file 而不是cat file | grep pattern

标签: bash shell


【解决方案1】:

当使用包含命令扩展的字符串分配变量时,返回码是正在扩展的(最右边的)命令的返回码。

换句话说,你可以只使用赋值作为条件:

if grepOutput="$(cat 'file' | grep 'match_word')"
then
  echo "There was a match"
  read -r a b <<< "${grepOutput}"
  (etc)
else
  echo "No match"
fi

【讨论】:

    【解决方案2】:

    您可以通过将搜索输出存储在一个变量中并查看它是否为空来避免重复使用grep

    你的脚本版本没有双 grep

    #!/bin/bash
    
    grepOutput="$(grep 'match_word' file)"
    
    if [ ! -z "$grepOutput" ]; then
        read a b <<< "${grepOutput}"
    fi
    

    对上述脚本的优化(您也可以删除临时变量)

    #!/bin/bash
    
    grepOutput="$(grep 'match_word' file)"
    
    [[ ! -z "$grepOutput" ]] && (read a b <<< "${grepOutput}")
    

    使用 double-grep 一次检查 if 条件和一次解析搜索结果将类似于:-

    #!/bin/bash
    
    if grep -q 'match_word' file; then
        grepOutput="$(grep 'match_word' file)"
        read a b <<< "${grepOutput}"
    fi
    

    【讨论】:

      【解决方案3】:

      这是你想要达到的目标吗?

      grep 'match_word' file ; echo $?
      

      $? 有一个之前运行的命令的返回值。
      如果您想跟踪返回值,使用$? 设置 PS1 也很有用。

      参考:Bash Prompt with Last Exit Code

      【讨论】:

      • 感谢您的回答。我只想在文件包含匹配单词的行时读取(或分析)匹配的行。为此,我使用了两次grep,但我觉得它效率不高。如果可能的话,我想只用一个 grep 来做。
      • @mora 抱歉误解了您的意图 - 如果您只想在找到匹配的单词时进一步分析 grep 输出,您可以评估 $?在 grep 之后:
      • @Ryota :感谢您回答我模棱两可的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多