Можно ли передать вывод ispell в массив? - PullRequest
0 голосов
/ 04 апреля 2011

Мне нужно каким-то образом получить выходные данные ispell -l в массив, чтобы я мог их циклически просматривать

Пока у меня есть это

cat $1 | ispell -l

Я пытался читать их построчно в массив, но у меня это не сработало

есть предложения?

Ответы [ 5 ]

2 голосов
/ 06 апреля 2011

На самом деле это намного проще, чем любые ответы, предоставленные до сих пор. Вам не нужно вызывать какие-либо внешние двоичные файлы, такие как cat или делать какие-либо циклы.

Просто сделайте:

array=( $(ispell -l < $1) )
2 голосов
/ 06 апреля 2011

Недавний bash поставляется с mapfile или readarray:

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

( этот пример эффективно возвращает ispell -l < "$1"|wc -l)

остерегайтесь ошибкисделайте, например, ls | readarray, это не будет работать, потому что readarray будет в подоболочке из-за конвейера.Используйте только перенаправление ввода.


   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 голос
/ 04 апреля 2011

В оболочке нет такого понятия, как массив.(У 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 (У меня не установлено и у меня нет времени на его сборку), чтобы сказать вам, что из вышеперечисленного является правильным вариантом.

0 голосов
/ 06 апреля 2011

Вы можете передать результат от 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 имеет лучшую производительность для перебора файлов, чем оболочка.

0 голосов
/ 05 апреля 2011
#!/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
...