【问题标题】:find pattern in multiple files and perform some action on them在多个文件中查找模式并对它们执行一些操作
【发布时间】:2020-10-21 05:40:08
【问题描述】:

我有 2 个文件 - file1.txt 和 file2.txt。 我想设置一个条件,只有当两个文件中都存在模式“xyz”时,才会在两个文件上运行命令。即使一个文件未能具有该模式,该命令也不应该运行。此外,我需要同时将这两个文件传递给 grep 或 awk 命令,因为我在另一种工作流语言中使用此代码。 我用 grep 编写了一些代码,但即使模式存在于其中一个文件中,此代码也会执行操作,这不是我想要的。如果有更好的方法,请告诉我。

if grep "xyz" file1.txt file2.txt; then
     my_command file1.txt file2.txt 
else 
     echo " command cannot be run on these files"
fi 

谢谢!

【问题讨论】:

标签: awk grep


【解决方案1】:

这个awk 应该适合你:

awk -v s='xyz' 'FNR == NR {
   if ($0 ~ s) {
      ++p
      nextfile
   }
   next
}
FNR == 1 {
   if (!p) exit 1
}
{
   if ($0 ~ s) {
      ++p
      exit
   }
}
END {
   exit p < 2
}' file1 file2

如果在两个文件中都找到了给定的字符串,它将以0 退出,否则将以1 退出。

【讨论】:

    【解决方案2】:

    Cyrus 删除的答案中抢救代码:

    if grep -q "xyz" file1.txt && grep -q "xyz" file2.txt; then
      echo "xyz was found in both files"
    else
      echo "xyz was found in one or no file"
    fi
    

    如果您需要运行单个命令,请将其保存为脚本,然后在您的条件下运行该脚本。

    #!/bin/sh
    grep -q "xyz" "$1" && grep -q "xyz" "$2"
    

    如果你把它保存在你的PATH 中并命名为grepboth(保存时不要忘记chmod a+x grepboth)你的条件现在可以写出来了

    grepboth file1.txt file2.txt
    

    或者grepall 接受搜索表达式和文件列表;

    #!/bin/sh
    what=$1
    shift
    for file; do
        grep -q "$what" "$file" || exit
    done
    

    这可以用作

    grepall "xyz" file1.txt file2.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 2014-02-05
      相关资源
      最近更新 更多