【问题标题】:How do I see if the output of one command is in the output of another?如何查看一个命令的输出是否在另一个命令的输出中?
【发布时间】:2021-09-14 16:44:11
【问题描述】:

我有两个命令。第一个,当存储在脚本变量中时,会给出如下输出:

one two three four five

第二个也给出了一个列表,但是第一个命令中的某些项目可能会丢失:

one three five

如果项目在第一个命令中但不在第二个命令中,我希望我的脚本执行某些操作。所有项目都没有空格(它们往往是kabab-format)。如何在 Bash 中做到这一点?

【问题讨论】:

  • 将这两个输出保存到一个数组中,这将为您提供所需的所有控制。
  • 请参阅stackoverflow.com/questions/3685970/… 了解如何测试数组是否包含值。循环第一个数组,并测试第二个数组是否包含该值。

标签: bash comm


【解决方案1】:

一种使用当前变量的方法,并依赖于单个值不包含嵌入空格的事实:

$ var1='one two three four five'
$ var2='one three five'
$ comm -23 <(printf "%s\n" ${var1} | sort) <(printf "%s\n" ${var2} | sort)
four
two

注意:不要${var1}${var2} 引用括在双引号中,即我们希望进行分词当喂printf 电话时


另一个使用关联数组来跟踪唯一值的想法:

var1='one two three four five'
var2='one three five'

unset      arr
declare -A arr

for f in ${var1}          # use ${var1} values as indices for arr[]
do
    arr[${f}]=1           # '1' has no meaning other than to fill requirement of assigning a value in order to create the array entry
done

for f in ${var2}          # delete ${var2} indices from arr[]
do
    unset arr[${f}]
done


for i in "${!arr[@]}"     # display arr[] indices that remain
do
    echo "${i}"
done

# one-liners (sans comments)

for f in ${var1}; do arr[${f}]=1; done
for f in ${var2}; do unset arr[${f}]; done
for i in "${!arr[@]}"; do echo "${i}"; done

这会生成:

two
four

注意事项:

  • 再次,不要${var1}${var2}引用用双引号括起来,即我们希望进行分词
  • 如果如此倾向于 OP 可以在单个 awk 脚本中执行相同的添加/删除数组操作
  • 第一个循环(从${var1} 填充arr[])将消除来自${var1} 的重复项,例如,var1='one one one' 将导致单个数组条目:arr[one]=1

【讨论】:

    【解决方案2】:

    关于我的评论 [1],我会这样处理:

    #!/bin/bash
    
    res1=(one two three four five)
    res2=(one three five)
    
    for value in "${res1[@]}"; do
        if [[ ! "${res2[*]}" =~ "${value}" ]]; then
    
            # Do action
            echo "'$value' does not exist in res2"
    
            # Possibly stop for loop
            break
        fi
    done
    

    使用break,这将显示:

    'two' does not exist in res2
    

    没有break,它将显示:

    'two' does not exist in res2
    'four' does not exist in res2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 2019-06-23
      • 2015-08-18
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多