0

I have a text file that looks like so:

:SomeWord:::SomeOtherWord:::MaybeAnotherWord::

Assuming that I don't know how many ":" are between words or even how many words there are, but every word is after a ":", I want to take this text file in Linux terminal and set 2 local vars to the first and second word found.

I have tried to make an array from the text file and then grab the 0 and 1 indexes but it didn't work like I thought.

~# myarray=$(cat mytextfile.txt | tr ":" "\n")
~# for line in $myarray ; do echo "[$line]"; done
[SomeWord]
[SomeOtherWord]
[MaybeAnotherWord]

ok that looks like it worked but then when I try to grab by index I get unexpected results..

~# echo ${myarray[0]}
SomeWord SomeOtherWord MaybeAnotherWord
~# echo ${myarray[1]}

~#

I don't know if I'm splitting the file wrong?

codeforester
  • 39,467
  • 16
  • 112
  • 140
erik
  • 4,946
  • 13
  • 70
  • 120

1 Answers1

2

You did not create an array, but just a normal variable. To create an array you have to write () arround the $() again:

myarray=($(cat mytextfile.txt | tr ":" "\n"))

which can also be written as:

myarray=($(tr ":" "\n" < mytextfile.txt))
codeforester
  • 39,467
  • 16
  • 112
  • 140
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • No, it creates an array of length 3. Just try it. If `$()` was quoted (`"$()"`) then you would be right. – Socowi Mar 17 '17 at 18:03
  • I had not quoted it. Not sure if `IFS` caused an issue. I tried your commands in a new Bash session and it worked. Edited your answer and upvoted. – codeforester Mar 17 '17 at 18:18