Zsh: read lines from file into array
#!/bin/zsh
zmodload zsh/mapfile
FNAME=/path/to/some/file.txt
FLINES=( "${(f)mapfile[$FNAME]}" )
LIST="${mapfile[$FNAME]}" # Not required unless stuff uses it
integer POS=1 # Not required unless stuff uses it
integer SIZE=$#FLINES # Number of lines, not required unless stuff uses it
for ITEM in $FLINES
# Do stuff
(( POS++ ))
done
You have some strange things in your code:
- Why are you splitting
LIST
each time instead of making it an array variable? It is just a waste of CPU time. - Why don’t you use
for ITEM in ${(f)LIST}
? - There is a possibility to directly ask zsh about array length:
$#ARRAY
. No need in determining the index of the last occurrence of the last element. POS
gets the same value asSIZE
in your code. Hence it will iterate only once.- Brackets are problems likely because of 3.:
(I)
is matching against a pattern. Do read documentation.
I know it's been a lot of time since the question was answered but I think it's worth posting a simpler answer (which doesn't require the zsh/mapfile external module):
#!/bin/zsh
for line in "${(@f)"$(</path/to/some/file.txt)"}"
{
// do something with each $line
}