Split string into an array in Bash

后端 未结 22 2614
故里飘歌
故里飘歌 2020-11-22 04:24

In a Bash script I would like to split a line into pieces and store them in an array.

The line:

Paris, France, Europe

I would like

22条回答
  •  日久生厌
    2020-11-22 04:43

    We can use tr command to split string into the array object. It works both MacOS and Linux

      #!/usr/bin/env bash
      currentVersion="1.0.0.140"
      arrayData=($(echo $currentVersion | tr "." "\n"))
      len=${#arrayData[@]}
      for (( i=0; i<=$((len-1)); i++ )); do 
           echo "index $i - value ${arrayData[$i]}"
      done
    

    Another option use IFS command

    IFS='.' read -ra arrayData <<< "$currentVersion"
    #It is the same as tr
    arrayData=($(echo $currentVersion | tr "." "\n"))
    
    #Print the split string
    for i in "${arrayData[@]}"
    do
        echo $i
    done
    

提交回复
热议问题