从数组中删除最后一个元素 [英] Remove the last element from an array
问题描述
我想删除数组中的最后一个条目,并且我希望数组在我使用 ${#array[@]}
时显示它少了 1 个条目.这是我正在使用的当前行:
unset GreppedURLs[${#GreppedURLs[@]} -1]
请纠正我并告诉我正确的方法.
你的答案(几乎)是正确的 对于非稀疏索引数组¹:
unset 'arr[${#arr[@]}-1]'
<块引用>
Bash 4.3 或更高版本添加了这个新语法来做同样的事情:
取消设置 arr[-1]
(注意单引号:它们可以防止路径名扩展).
演示:
arr=( a b c )回声 ${#arr[@]}
<块引用>
3
for a in "${arr[@]}";做 echo "$a";完毕
<块引用>
a乙C
unset 'arr[${#arr[@]}-1]'for a in "${arr[@]}";做 echo "$a";完毕
<块引用>
a乙
重点
echo ${#arr[@]}
<块引用>
2
(GNU bash, 版本 4.2.8(1)-release (x86_64-pc-linux-gnu))
<小时>¹ @Wil 提供了一个很好的答案,适用于各种数组
I want to remove the last entry in my array, and I want the array to show me that it has 1 less entry when I am using the ${#array[@]}
. This is the current line I am using:
unset GreppedURLs[${#GreppedURLs[@]} -1]
Please correct me and show me the right way.
The answer you have is (nearly) correct for non-sparse indexed arrays¹:
unset 'arr[${#arr[@]}-1]'
Bash 4.3 or higher added this new syntax to do the same:
unset arr[-1]
(Note the single quotes: they prevent pathname expansion).
Demo:
arr=( a b c )
echo ${#arr[@]}
3
for a in "${arr[@]}"; do echo "$a"; done
a b c
unset 'arr[${#arr[@]}-1]'
for a in "${arr[@]}"; do echo "$a"; done
a b
Punchline
echo ${#arr[@]}
2
(GNU bash, version 4.2.8(1)-release (x86_64-pc-linux-gnu))
¹ @Wil provided an excellent answer that works for all kinds of arrays
这篇关于从数组中删除最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!