如何查看一个命令的输出是否在另一个命令的输出中?

How do I see if the output of one command is in the output of another?

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

one two three four five

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

one three five

如果项目在第一个命令中而不是第二个命令中,我希望我的脚本执行某些操作。 None 个项目会有空格(它们往往是 kabab-format)。我如何在 Bash 中执行此操作?

关于我的评论 ,我将按以下方式处理:

  • 循环 res1
    • If current value does not exist in res2
      • 预成型动作
      • 如果需要,请停止 for
#!/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

一种方法使用当前变量,并依赖于各个值不包含嵌入白色这一事实 space:

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

注意: do not 用双引号括起 ${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 脚本中执行相同的 add/remove 数组操作
  • 第一个循环(从 ${var1} 填充 arr[])将消除 ${var1} 中的重复项,例如,var1='one one one' 将导致单个数组条目:arr[one]=1