gpt4 book ai didi

arrays - 未提供起始索引时,bash 数组切片如何工作?

转载 作者:行者123 更新时间:2023-11-29 09:49:58 24 4
gpt4 key购买 nike

我正在查看一个脚本,但我无法确定发生了什么。

这是一个例子:

# Command to get the last 4 occurrences of a pattern in a file
lsCommand="ls /my/directory | grep -i my_pattern | tail -4"

# Load the results of that command into an array
dirArray=($(echo $(eval $lsCommand) | tr ' ' '\n'))

# What is this doing?
yesterdaysFileArray=($(echo ${x[@]::$((${#x[@]} / 2))} | tr ' ' '\n'))

这里发生了很多事情。我了解数组的工作原理,但我不知道如果 $x 从未声明过,它是如何被引用的。

我看到 $((${#x[@]}/2}} 正在获取元素的数量并将其分成两半,而 tr 用于创建数组。但是还有什么事情发生了?

最佳答案

我认为最后一行是 bash${array[@]:1:2} 形式的数组切片模式,其中 array[@ ] 返回数组的内容,:1:2 取长度为 2 的切片,从索引 1 开始。

因此对于您的情况,尽管您采用的是起始索引 empty 因为您没有指定任何索引并且长度为数组计数的一半。

但是在 bash 中有很多更好的方法可以做到这一点,如下所示。不要使用 eval 并使用 shell 本身的内置 globbing 支持

cd /my/directory 
fileArray=()
for file in *my_pattern*; do
[[ -f "$file" ]] || { printf '%s\n' 'no file found'; return 1; }
fileArray+=( "$file" )
done

printf '%s\n' "${fileArray[@]::${#fileArray[@]}/2}"

关于arrays - 未提供起始索引时,bash 数组切片如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54557499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com