0

I'm trying to store each word from a file (named f1.txt) in an array (in bash), and then I want to print each element of the array. I tried something like this:

n=0
for varWord in $(cat f1.txt);
do
  word[$n]=$varWord
  $((n++))
done

for((i=0;i<n;i++));
do
  echo $((word[i]))
done

I've also tried this (In fact, it was my first approach, as I would also prefer not to use an additional variable -- varWord, like I did above):

n=0
for word[$n] in $(cat f1.txt);
do
  $((n++))
done

for((i=0;i<n;i++));
do
  echo $((word[i]))
done
  • 2
    `for i in $(cat)` is a common __anti__-pattern - you should not do that. [bashfaq How to read a file line by line?](https://mywiki.wooledge.org/BashFAQ/001) – KamilCuk Feb 24 '20 at 23:03
  • 5
    Does this answer your question? [Creating an array from a text file in Bash](https://stackoverflow.com/questions/30988586/creating-an-array-from-a-text-file-in-bash) and [Print array elements on separate lines in Bash?](https://stackoverflow.com/questions/15691942/print-array-elements-on-separate-lines-in-bash) – KamilCuk Feb 24 '20 at 23:04

1 Answers1

0
read -r -d '' -a words <inputfile.txt

That's all it needs.

Léa Gris
  • 17,497
  • 4
  • 32
  • 41