以下是我创建bash数组的方法:
while read line
do
myarr[$index]=$line
index=$(($index+1))
done < lines.txt
Run Code Online (Sandbox Code Playgroud)
文件"lines.txt"由以下字符串组成
hello big world!
how are you
where am I
Run Code Online (Sandbox Code Playgroud)
创建之后,${myarr[@]}我可以轻松访问此数组发布中的每个元素(行)
echo ${myarr[2]}
Run Code Online (Sandbox Code Playgroud)
但是如果我想提取world!呢?是否有可能world!从0元素中提取myarr?最重要的是,是否可以从myarr元素中提取任何最后一个单词?
我知道在python中你可以做到myarr[0][3]这一点就可以了,bash怎么样?
小智 21
这是众多方法之一
set ${myarr[2]}
echo $3
Run Code Online (Sandbox Code Playgroud)
使用索引打印数组中的特定元素:
echo ${my_array[2]}
Run Code Online (Sandbox Code Playgroud)
要打印数组中的所有元素,请执行以下操作:
for i in "${my_array[@]}"
do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
您可以使用变量扩展中的修饰符从字符串(这是数组元素)中提取单词:( #删除前缀),##(删除前缀,贪婪),%(删除后缀)和%%(删除后缀,贪婪).
$ myarr=('hello big world!' 'how are you' 'where am I')
$ echo "${myarr[0]}" # Entire first element of the array
hello big world!
$ echo "${myarr[0]##* }" # To get the last word, remove prefix through the last space
world!
$ echo "${myarr[0]%% *}" # To get the first word, remove suffix starting with the first space
hello
$ tmp="${myarr[0]#* }" # The second word is harder; first remove through the first space...
$ echo "${tmp%% *}" # ...then get the first word of what remains
big
$ tmp="${myarr[0]#* * }" # The third word (which might not be the last)? remove through the second space...
$ echo "${tmp%% *}" # ...then the first word again
world!
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,你可以在这里得到相当的幻想,但在某些时候@chepner建议把它变成一个数组变得容易了.此外,我建议用于提取第二个等词的公式有点脆弱:如果你使用我的公式提取只有两个单词的字符串的第三个单词,第一个修剪将失败,它将结束打印第一个(!)字而不是空白.另外,如果你连续有两个空格,这会将它视为一个零长度的单词,每一行都有一个空格......
顺便说一句,在构建数组时,我认为使用+=(newelement)它比使用它更清晰,而不是明确地跟踪数组索引:
myarr=()
while read line, do
myarr+=("$line")
done < lines.txt
Run Code Online (Sandbox Code Playgroud)
类似于stephen-penny 的回答,但没有覆盖 shell/函数位置参数。
a=(${myarr[2]})
echo ${a[3]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42774 次 |
| 最近记录: |