我可以将ispell输出管道输出到阵列吗?

时间:2011-04-04 17:27:04

标签: arrays shell unix pipe

我需要以某种方式将ispell -l的输出转换为数组,以便我可以遍历它们。

到目前为止我已经有了这个

cat $1 | ispell -l

我试图将它们逐行读入数组,但这对我没有用

有什么建议吗?

5 个答案:

答案 0 :(得分:2)

最近的bash附带mapfilereadarray

   readarray stuff < <(ispell -l < "$1")
   echo "number of lines: ${#stuff[@]}"

此示例有效地返回ispell -l < "$1"|wc -l

要小心做错了,例如ls | readarray,它不起作用,因为readarray因为管道而在子shell中。仅使用输入重定向。


   mapfile [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
   readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
          Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the -u option is supplied.  The vari‐
          able MAPFILE is the default array.  Options, if supplied, have the following meanings:
          -n     Copy at most count lines.  If count is 0, all lines are copied.
          -O     Begin assigning to array at index origin.  The default index is 0.
          -s     Discard the first count lines read.
          -t     Remove a trailing newline from each line read.
          -u     Read lines from file descriptor fd instead of the standard input.
          -C     Evaluate callback each time quantum lines are read.  The -c option specifies quantum.
          -c     Specify the number of lines read between each call to callback.

          If  -C  is specified without -c, the default quantum is 5000.  When callback is evaluated, it is supplied the index of the next array element
          to be assigned as an additional argument.  callback is evaluated after the line is read but before the array element is assigned.

          If not supplied with an explicit origin, mapfile will clear array before assigning to it.

          mapfile returns successfully unless an invalid option or option argument is supplied, array is invalid or unassignable, or if array is not an
          indexed array.

答案 1 :(得分:2)

它实际上比迄今提供的任何答案容易得多。您不需要调用任何外部二进制文件,例如cat或执行任何循环。

简单地说:

array=( $(ispell -l < $1) )

答案 2 :(得分:1)

shell中没有数组这样的东西。 (Bash和zsh有数组扩展;但是如果你发现自己认为bash或zsh扩展对脚本有帮助,那么正确的选择是在perl或python中重写./ digression)

你真正想要的是这些结构之一:

ispell -l < "$1" | while read line; do
    ... take action on "$line" ...
done

for word in $(ispell -l < "$1"); do
    ... take action on "$word" ...
done

我需要更多地了解您正在尝试做什么以及ispell -l的输出格式(我没有安装它,现在没有时间来构建它)来告诉我你是上面哪一个是正确的选择。

答案 3 :(得分:0)

#!/bin/bash

declare -a ARRAY_VAR=(`cat $1 | ispell -l`)

for var in ${ARRAY_VAR[@]}
do
    place your stuff to loop with ${VAR} here
done

答案 4 :(得分:0)

您可以将ispell的结果传递给awk

ispell -l $file | awk '
{
  print "Do something with $0"
  #Or put to awk array
  array[c++]=$0
}
END{
  print "processing the array here if you want"
  for(i=1;i<=c;i++){
     print i,array[i]
  }
}
'

Awk在迭代文件方面的性能优于shell。