Zsh:从文件读取行到数组中 [英] Zsh: read lines from file into array

查看:212
本文介绍了Zsh:从文件读取行到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取一个文件作为行数组,然后遍历它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

您的代码中有一些奇怪的东西:


  1. 每次拆分 LIST 而不是将它变成数组变量?
  2. 为什么不在$ {(f)LIST}中使用作为ITEM中的项目

  3. 有可能直接询问zsh数组的长度: $#ARRAY
  4. POS 获得与 SIZE 在你的代码中。因此,它只会迭代一次。
  5. 方括号可能是因为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:

  1. Why are you splitting LIST each time instead of making it an array variable? It is just a waste of CPU time.
  2. Why don’t you use for ITEM in ${(f)LIST}?
  3. 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.
  4. POS gets the same value as SIZE in your code. Hence it will iterate only once.
  5. Brackets are problems likely because of 3.: (I) is matching against a pattern. Do read documentation.

这篇关于Zsh:从文件读取行到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆