【问题标题】:bash script check strings in filebash脚本检查文件中的字符串
【发布时间】:2013-03-02 17:47:02
【问题描述】:

我该怎么做:

if !("abc" in file1 and "def" in file2)
then
  echo "Failed"
fi

我已经知道如何检查 file1:grep -Fxq "abc" file1 中的“abc”,但我无法让 if not (command1 and command2) 部分工作。

【问题讨论】:

标签: linux bash scripting


【解决方案1】:

你几乎是对的。只需在感叹号和 grep 命令之间添加一个空格即可:

if ! (grep -Fxq "abc" file1 && grep -Fxq "def" file2); then
     echo "Failed"
fi

假设bash,则不需要额外的else

请注意,使用括号在子 shell 环境中运行 grep,作为子 shell 进程。您可以通过使用花括号轻松避免这种情况(这称为组命令):

if ! { grep -Fxq "abc" file1 && grep -Fxq "def" file2; }; then
     echo "Failed"
fi

请注意,您需要更多的空格和一个额外的分号——bash 语法是不是很有趣!?!

【讨论】:

  • 什么具体不起作用?你在使用bash{ ... } 构造是bash 扩展)?
【解决方案2】:

你可以这样做:

$ grep -Fxq "abc" file1 && grep -Fxq "def" file2 || echo "Failed"

这使用 bash 逻辑运算符 AND && 和 OR ||

这可以分成多行,例如:

$ grep -Fxq "abc" file1 && 
> grep -Fxq "def" file2 ||
> echo "Failed" 

【讨论】:

    【解决方案3】:
    if (grep -Fxq "abc" file1 && grep -Fxq "def" file2);
    then
      echo ""
    else
      echo "failed"
    fi
    

    【讨论】:

    • 完全一样,我写过,+1
    • @chepner 我使用 OP 的代码 sn-p 来回答他的问题。现在更正了。
    猜你喜欢
    • 2022-11-02
    • 2016-03-04
    • 2019-11-03
    • 2013-11-30
    • 2013-01-23
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多