bash 比较字符串与字符串列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12768265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:29:01  来源:igfitidea点击:

bash compare a string vs a list of strings

regexbash

提问by kfmfe04

Suppose I have the following code in bash:

假设我在 bash 中有以下代码:

#!/bin/bash

bad_fruit=( apple banana kiwi )
for fname in `ls`
do
  # want to check if fname contains one of the bad_fruit
  is_bad_fruit=??? # <------- fix this line
  if [ is_bad_fruit ]
  then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done

How do I fix is_bad_fruit so that it is true if fname contains one of the bad_fruit strings?

如何修复 is_bad_fruit 以便 fname 包含 bad_fruit 字符串之一时为真?

回答by Gilles Quenot

Try the following code :

试试下面的代码:

#!/bin/bash

bad_fruit=( apple banana kiwi )
re="$(printf '%s\n' "${bad_fruit[@]}" | paste -sd '|')"

for fname in *; do
  # want to check if fname contains one of the bad_fruit
  if [[ $fname =~ $re ]]; then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done

Take care of useless use of ls

注意ls无用使用

lsis a tool for interactively looking at file information. Its output is formatted for humans and will cause bugs in scripts. Use globs or find instead. Understand why: http://mywiki.wooledge.org/ParsingLs

ls是一种交互式查看文件信息的工具。它的输出是为人类格式化的,会导致脚本中的错误。使用 globs 或 find 代替。了解原因http: //mywiki.wooledge.org/ParsingLs

回答by Ansgar Wiechers

Another option (using grepwith an inner loop and evaluating the exit code):

另一种选择(grep与内部循环一起使用并评估退出代码):

#!/bin/bash

bad_fruit=( apple banana kiwi )
for fname in *; do
  for fruit in "${bad_fruit[@]}"; do
    echo "$fruit"
  done | grep "$fname"
  if [ $? -eq 0 ]; then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done