'How to read lines from a file into an array?
I'm trying to read in a file as an array of lines and then iterate over it with zsh. The code I've got works most of the time, except if the input file contains certain characters (such as brackets). Here's a snippet of it:
#!/bin/zsh
LIST=$(cat /path/to/some/file.txt)
SIZE=${${(f)LIST}[(I)${${(f)LIST}[-1]}]}
POS=${${(f)LIST}[(I)${${(f)LIST}[-1]}]}
while [[ $POS -le $SIZE ]] ; do
ITEM=${${(f)LIST}[$POS]}
# Do stuff
((POS=POS+1))
done
What would I need to change to make it work properly?
Solution 1:[1]
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
}
Solution 2:[2]
Let's say, for the purpose of example, that file.txt contains the following text:
one
two
three
The solution depends on whether or not you'd like to elide the empty lines in file.txt:
Creating an array
linesfrom filefile.txt, eliding empty lines:typeset -a lines=("${(f)"$(<file.txt)"}") print ${#lines}Expected output:
3
Creating an array
linesfrom filefile.txt, without eliding empty lines:typeset -a lines=("${(@f)"$(<file.txt)"}") print ${#lines}Expected output:
5
In the end, the difference in the resulting array is a result of whether or not the parameter expansion flag (@) is provided during brace expansion.
Solution 3:[3]
while read -r line;
do ARRAY+=("$line");
done < file.txt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | chahu418 |
| Solution 3 | elig |
