bash 在数组上使用 GREP 来查找单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21058210/
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-10 00:36:28  来源:igfitidea点击:

Use GREP on array to find words

arraysbashshelldebuggingcommand-line

提问by Computernerd

Given the following array in Shell Programming

给定以下 Shell 编程中的数组

foo=(spi spid spider spiderman bar lospia)

foo=(spi spid 蜘蛛蜘蛛侠酒吧 lospia)

I would like to use GREP to search for all words in the array which has the 3 letters spi

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

Correct output : spi spi spider spiderman lospia

正确输出:spi spi蜘蛛蜘蛛侠lospia

I have tried something like this

我试过这样的事情

foo=(spi spid spider spiderman)

grep "spi" foo

But it seems it is wrong , what is the correct way to go about it ???

但它似乎是错误的,正确的做法是什么???

采纳答案by CrazyCasta

The following will print out all words that contain spi:

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

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

回答by mockinterface

The simplest solution would be to pipe the array elements into grep:

最简单的解决方案是将数组元素通过管道传输到 grep 中:

printf -- '%s\n' "${foo[@]}" | grep spi

A couple of notes:

一些注意事项:

printfis a bash builtin, and you can look it up with man printf. The --option tells printf that whatever follows is not a command line option. That guards you from having strings in the fooarray being interpreted as such.

printf是一个内置的 bash,你可以用man printf. 该--选项告诉 printf 后面的内容不是命令行选项。这可以防止您将foo数组中的字符串解释为这样。

The notation of "${foo[@]}"expands all the elements of the array as standalone arguments. Overall the words in the array are put into a multi-line string and are piped into grep, which matches every individual line against spi.

的符号"${foo[@]}"将数组的所有元素扩展为独立参数。总的来说,数组中的单词被放入一个多行字符串中,并通过管道传送到 grep,它与spi匹配每一行。

回答by John1024

IFS=$'\n' ; echo "${foo[*]}" | grep spi

This produces the output:

这会产生输出:

spi
spid
spider
spiderman
lospia

回答by David Pointon

If the requirement is to run the script/extract under the exit-on-error shell flag ('-e') and unnecessarily exiting the script/extract whilst also avoiding the tedium of wrapping the code in "set +e" … "set -e", I always use case since unlike grep(1) or test(1), it (case) doesn't update $? …

如果要求是在出错时退出 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