【问题标题】:Two conditions with negation bash for filenameTwo conditions with negation bash for filename
【发布时间】:2022-12-01 21:33:19
【问题描述】:

I want to echo files that does not contain a substring "cds" or "rna" in their filenames.

I use the following code:

for genome in *
do
if [ ! "$genome" == *"cds"* ] || [ ! "$genome" == *"rna"* ]
then
    echo $genome
fi
done

The code does not return any error but it keeps printing files that have the substrings indicated in the file name. How can I correct this? Thank you!

【问题讨论】:

  • In this test, you want && rather than ||, because you want filenames that don't contain "cds"and alsodon't contain "rna". See "Why does non-equality check of one variable against many values always return true?" Also, read about De Morgan's laws for how to combine negative tests.
  • The * does not act as a wildcard pattern match (as you can verify with [ c == c* ] && echo true. Aside from this, the logic itself is broken, as you try to find names which either don't contain cds or don't contain rna (i.e. you try to exclude those which contain bothcdsandrna).

标签: bash if-statement


【解决方案1】:

There's two separate mistakes:

  • When using * in Bash comparisons, you need to use two sets of brackets, so [ ... ] should be [[ ... ]].
  • I think you really mean "files that does not contain a substring "cds"and also not"rna" in their filenames. That is, the 'or' (||) should be an 'and' (&&).
for genome in *
do
if [[ ! "$genome" == *"cds"* ]] && [[ ! "$genome" == *"rna"* ]]
then
    echo $genome
fi
done

【讨论】:

    【解决方案2】:

    The condition should be written as

    [[ ! $genome =~ cds|rna ]] && echo $genome
    

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2012-12-12
      • 2013-12-20
      • 2022-12-01
      • 2019-10-29
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      相关资源
      最近更新 更多