0

I have a command

cat test.log | cut -d':' -f1 | sort -u  

which returns: 8967 4376 0989 4321

I want to put it in an array so I did

arr=$(cat test.log | cut -d':' -f1 | sort -u)  

I can print it out with

for i in $arr; do  
    echo ${i}  
done  

output: 8967 4376 0989 4321

but when I try to access it by echoing each element

echo ${arr[0]}  

returns 1234 1234 1902 4224 5883 8273 and

echo ${arr[1]}  

returns nothing

I have also tried putting each element in with(sudo code)

for i in command  
arr+=i  

which did not work either. Can someone tell me what is the cause of this?

EDIT:
based on the post charles recommended, I tried going with map but it gives me a syntax error. Is this how im supposed to write it?

mapfile -t my_array < <( cat test.log | cut -d':' -f1 | sort -u )
llssff
  • 119
  • 7
  • thank you felix for the stylish edit. How did you do the code blocks? I led with 4 spaces but it still showed up as plain text. – llssff Mar 18 '19 at 22:46
  • 1
    You need to have vertical whitespace surrounding the four-space indents. – Charles Duffy Mar 18 '19 at 22:47
  • 1
    You need an emtpy line before the code block (and possibly after). – Felix Kling Mar 18 '19 at 22:47
  • 2
    BTW, generally speaking, it's best to avoid using `cat` unless you absolutely can't avoid it. For some commands it's only a slight inefficiency (`cat test.log | cut -d: -f1` is only slightly slower than `cut -d: -f1 – Charles Duffy Mar 18 '19 at 22:51

0 Answers0