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

时间:2012-10-07 11:07:43

标签: regex 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

如何修复is_bad_fruit,如果fname包含bad_fruit字符串之一,则为true?

2 个答案:

答案 0 :(得分:5)

请尝试以下代码:

#!/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

照顾useless use of ls

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

答案 1 :(得分:2)

另一个选项(使用带有内循环的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