bash split string into array
来源:互联网 发布:linux cut uniq 编辑:程序博客网 时间:2024/05/16 12:51
In a bash script I would like to split a line into pieces and put them into an array.
The line:
Paris, France, Europe
I would like to have them in an array like this:
array[0] = Paris
array[1] = France
array[2] = Europe
I would like to use a simple code, the command's speed doesn't matter. Any ideas?
IFS=', ' read -a array <<< "$string"
To access an individual element:
echo "${array[0]}"
To iterate over the elements:
for element in "${array[@]}"
do
echo "$element"
done
To get both the index and the value:
for index in "${!array[@]}"
do
echo "$index ${array[index]}"
done
The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.
unset "array[1]"
array[42]=Earth
To get the number of elements in an array:
echo "${#array[@]}"
As mentioned above, arrays can be sparse so you shouldn't use the length to get the last element. Here's how you can in Bash 4.2 and later:
echo "${array[-1]}"
in any version of Bash (from somewhere after 2.05b):
echo "$array[@]: -1:1}
- bash split string into array
- Split Array into Consecutive Subsequences
- Split String into Valid Words
- php Split an Array into N Arrays
- Split array into two equal sum subArray
- 659. Split Array into Consecutive Subsequences
- leetcode 659. Split Array into Consecutive Subsequences
- 659. Split Array into Consecutive Subsequences
- LeetCode #659 Split Array into Consecutive Subsequences
- Split Array into Consecutive Subsequences 解法
- 659. Split Array into Consecutive Subsequences
- leetcode 659. Split Array into Consecutive Subsequences
- Split Ruby array into sub array with slash
- Leetcode659——Split Array into Consecutive Subsequences
- 659. Split Array into Consecutive Subsequences 堆、优先级队列、哈希表
- LeetCode[659]Split Array into Consecutive Subsequences(Java)
- [LeetCode] 贪心算法之 Split Array into Consecutive Subsequence
- Split Array into Consecutive Subsequences问题及解法
- win 8 database mysql support is not compiled into this build of snort
- string::npos的一些说明
- Ubuntu14.04LTS中文输入法安装问题
- How to check the first character in a string in unix
- TotoiseSVN的基本使用方法
- bash split string into array
- XCL-Charts画曲线图(CurveChart) 例2
- C# 命名规范
- ios tableview 那些事(二十五)用故事板 自定义Tableview 不显示数据注意事项。
- Oracle oledb 打包并集成到程序安装包(VC ADO访问Oracle)
- 通过struts2的JSONResult返回json数据的配置
- UCM-001:Configuring Installer DisableNtfs8dot3 in window 7+
- java修改request的paramMap
- 依照测试用例分类(按功能)的结果生成对应的universe文件