I'm trying to read a line of text in bash using grep
, piped to tail
to get the final line of the file, and then slice the first three "words" (i.e. dividing them using space) of that line as elements of an array.
It works fine if I try to, e.g. loop over the elements in the output using a for
loop, and I get the list of elements I want:
[] foo=$(grep select file.txt | tail -n 1)
[] echo $foo
0.47331 5.11188 13.1615 # select
[] for x in $foo; do echo $x; done
0.47331
5.11188
13.1615
#
select
Exactly what I want it to do!
But if I try to get out an array with the first three elements of foo
, I cannot get it to work:
[] echo "${foo[@]:0:2}"
0.47331 5.11188 13.1615 # select 4.95294 13.5177
What's particularly weird is that those last two values at the end of the line are actually two values from the first line containing select
in file.txt
(and not even the first two items on that line, but the second and third!), so they shouldn't even be part of foo
at all...
Similarly, if I try and simply slice a single "word" from foo
, I get a weird output:
[] echo "${foo[0]}"
0.47331 5.11188 13.1615 # select
[] echo "${foo[1]}"
4.95294
(Again, that last value is a value that shouldn't, as I best understand it, even be in foo
, it's the second item on the first line with select
in file.txt
...).
I need to understand what is going on, and how to get out the output I want, namely an array 0.47331 5.11188 13.1615
.
foo=( $(grep select file.txt | tail -n 1) )
solve all your problems?echo "${foo[@]:0:2}"
... you haven't created afoo
array yet, so what did you expect this to do?