问题描述
我试图读取一个文件作为行数组,然后遍历它zsh,我得到的代码大部分时间工作,除非输入文件包含某些字符(如括号) 。下面是它的一个片段:
#!/ 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]];做
ITEM = $ {$ {(f)LIST} [$ POS]}
#做东西
((POS = POS + 1))
完成
这样做会更简单吗?
#!/ bin / zsh
zmodload zsh / mapfile
FNAME = / path / to / some / file.txt
FLINES =($ {(f)mapfile [$ FNAME]})
LIST =$ {mapfile [$ FNAME]}#不需要,除非东西使用它
整数POS = 1#不需要,除非东西使用它
整数SIZE = $#FLINES#行数,不需要,除非东西使用
在$ FLINES中的项目
#做东西
((POS ++))
endfor
您的代码中有一些奇怪的东西:
- 每次拆分
LIST
而不是将它变成数组变量?
- 为什么不在$ {(f)LIST}中使用
作为ITEM中的项目
? - 有可能直接询问zsh数组的长度:
$#ARRAY
。
-
POS
获得与 SIZE 在你的代码中。因此,它只会迭代一次。
- 方括号可能是因为3:
(I)
匹配模式。请阅读文档。
I'm trying to read in a file as an array of lines and then iterate over it zsh, and 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 be an easier way of doing this? I also need to count the number of lines in the file.
#!/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++ ))
endfor
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.
这篇关于Zsh:从文件读取行到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!