2015年10月12日 星期一

[Linux 常見問題] Split string into an array in Bash

Source From Here 
Question 
In a Bash script I would like to split a line into pieces and put them into an array. For example: 
  1. Paris, France, Europe  
I would like to have them in an array like this: 
array[0] = Paris
array[1] = France
array[2] = Europe

How-To 
Try this command: 
  1. IFS=', ' read -a array <<< "$string"  
To access an individual element: 
  1. echo "${array[0]}"  
To iterate over the elements: 
  1. for element in ${array[@]}  
  2. do  
  3.     echo "$element"  
  4. done  
To get both the index and the value: 
  1. for index in ${!array[@]}  
  2. do  
  3.     echo "$index ${array[index]}"  
  4. 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. To get the number of elements in an array: 
  1. 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: 
  1. echo "${array[-1]}"  
Below is the sample code: 
  1. #!/bin/bash  
  2. PWD=`pwd`  
  3. echo "Current PWD=$PWD"  
  4. IFS='/' read -a array <<< "$PWD"  
  5.   
  6. echo "There are ${#array[@]} element(s)."  
  7. for index in ${!array[@]}  
  8. do  
  9.     echo "$index ${array[index]}"  
  10. done  
Execution result sample: 
# ./test.sh
Current PWD=/root/tmp/test
There are 4 element(s).
0
1 root
2 tmp
3 test

Supplement 
Blog - Separate string into array from bash

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...