Arrays 使用数组上的GREP查找单词

Arrays 使用数组上的GREP查找单词,arrays,bash,shell,debugging,command-line,Arrays,Bash,Shell,Debugging,Command Line,给定Shell编程中的以下数组 foo=(蜘蛛人条lospia) 我想使用GREP搜索数组中包含3个字母的所有单词spi 正确输出:spi-spi-spiderman-lospia 我试过这样的东西 foo=(spi spid spider spiderman) grep "spi" foo 但这似乎是错误的,正确的方法是什么?下面将打印出包含spi的所有单词: foo=(spi spid spider spiderman bar) for i in ${foo[*]} do ech

给定Shell编程中的以下数组

foo=(蜘蛛人条lospia)

我想使用GREP搜索数组中包含3个字母的所有单词
spi

正确输出:spi-spi-spiderman-lospia

我试过这样的东西

foo=(spi spid spider spiderman)

grep "spi" foo

但这似乎是错误的,正确的方法是什么?

下面将打印出包含spi的所有单词:

foo=(spi spid spider spiderman bar)
for i in ${foo[*]}
do
    echo $i | grep "spi"
done

最简单的解决方案是将数组元素导入grep:

printf -- '%s\n' "${foo[@]}" | grep spi
几点注意:

printf是bash内置的,您可以使用
manprintf
查找它。
--
选项告诉printf后面的内容不是命令行选项。这可以防止
foo
数组中的字符串被解释为这样

“${foo[@]}”
表示法将数组的所有元素作为独立参数展开。总的来说,数组中的单词被放入一个多行字符串中,并通过管道传输到grep中,grep根据spi匹配每一行

这将产生以下输出:

spi
spid
spider
spiderman
lospia

如果要求在错误shell标志('-e')下运行脚本/提取,并且不必要地退出脚本/提取,同时避免将代码包装在“set+e”…“set-e”中的繁琐,我总是使用case,因为与grep(1)或test(1)不同,它(case)不会更新$

for e in "${foo[@]}" ; do 
    case "$f" in
        *spi*) echo $f ;;
    esac
done

可能值得将其转换回数组
bar=$(printf--'%s\n'${foo[@]}'| grep spi | tr'\n'')
for e in "${foo[@]}" ; do 
    case "$f" in
        *spi*) echo $f ;;
    esac
done