Split string into an array in Bash

后端 未结 22 2295
故里飘歌
故里飘歌 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 05:00

    Pure bash multi-character delimiter solution.

    As others have pointed out in this thread, the OP's question gave an example of a comma delimited string to be parsed into an array, but did not indicate if he/she was only interested in comma delimiters, single character delimiters, or multi-character delimiters.

    Since Google tends to rank this answer at or near the top of search results, I wanted to provide readers with a strong answer to the question of multiple character delimiters, since that is also mentioned in at least one response.

    If you're in search of a solution to a multi-character delimiter problem, I suggest reviewing Mallikarjun M's post, in particular the response from gniourf_gniourf who provides this elegant pure BASH solution using parameter expansion:

    #!/bin/bash
    str="LearnABCtoABCSplitABCaABCString"
    delimiter=ABC
    s=$str$delimiter
    array=();
    while [[ $s ]]; do
        array+=( "${s%%"$delimiter"*}" );
        s=${s#*"$delimiter"};
    done;
    declare -p array
    

    Link to cited comment/referenced post

    Link to cited question: Howto split a string on a multi-character delimiter in bash?

提交回复
热议问题