【问题标题】:Use GREP on array to find words在数组上使用 GREP 查找单词
【发布时间】:2014-01-30 05:54:39
【问题描述】:

在 Shell 编程中给定以下数组

foo=(spi spid spider 蜘蛛侠 bar lospia)

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

正确的输出:spi spi spider spiderman lospia

我尝试过类似的方法

foo=(spi spid spider spiderman)

grep "spi" foo

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

【问题讨论】:

    标签: arrays bash shell debugging command-line


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      几点说明:

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

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

      【讨论】:

      • 可能值得将其转换回数组bar=$(printf -- '%s\n' "${foo[@]}" | grep spi | tr '\n' ' ');
      • 绝对是这里最有帮助的答案。比我原来的bash for entry in "${foo[@]}"; do if echo "$entry" | grep spi &>/dev/null; then results+=("$entry") fi done 效率要高得多。这样做反而将性能提高了几个数量级:bash results+=($(printf "%s\n" "${foo[@]}" | grep spi))
      【解决方案3】:
      IFS=$'\n' ; echo "${foo[*]}" | grep spi
      

      这会产生输出:

      spi
      spid
      spider
      spiderman
      lospia
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-05-06
          • 1970-01-01
          • 1970-01-01
          • 2015-07-19
          • 2012-07-07
          • 1970-01-01
          • 2021-12-14
          相关资源
          最近更新 更多