Split string into an array in Bash

后端 未结 22 2265
故里飘歌
故里飘歌 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:48

    Since there are so many ways to solve this, let's start by defining what we want to see in our solution.

    1. Bash provides a builtin readarray for this purpose. Let's use it.
    2. Avoid ugly and unnecessary tricks such as changing IFS, looping, using eval, or adding an extra element then removing it.
    3. Find a simple, readable approach that can easily be adapted to similar problems.

    The readarray command is easiest to use with newlines as the delimiter. With other delimiters it may add an extra element to the array. The cleanest approach is to first adapt our input into a form that works nicely with readarray before passing it in.

    The input in this example does not have a multicharacter delimiter. If we apply a little common sense, it's best understood as comma separated input for which each element may need to be trimmed. My solution is to split the input by comma into multiple lines, trim each element, and pass it all to readarray.

    string='  Paris,France  ,   All of Europe  '
    readarray -t foo < <(tr ',' '\n' <<< "$string" |sed 's/^ *//' |sed 's/ *$//')
    declare -p foo
    
    # declare -a foo='([0]="Paris" [1]="France" [2]="All of Europe")'
    

提交回复
热议问题