我需要以某种方式得到ispell -l的输出到一个数组,以便我可以循环他们..
到目前为止我已经得到了这个
cat $1 | ispell -l
我试图逐行阅读他们到一个数组,但没有为我工作
有什么build议么?
最近bash带有mapfile
或readarray
:
readarray stuff < <(ispell -l < "$1") echo "number of lines: ${#stuff[@]}"
( 这个例子有效地返回ispell -l < "$1"|wc -l
)
提防例如ls | readarray
的错误 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.
这实际上比迄今为止提供的答案要容易得多。 你不需要调用任何外部的二进制文件,如cat
或做任何循环。
简单地做:
array=( $(ispell -l < $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
的输出格式(我没有安装它,现在没有时间来构建它)来告诉你上面哪个是正确的选择。
#!/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
你可以把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更好地遍历文件。