Loop through a comma-separated shell variable

前端 未结 8 1932
醉话见心
醉话见心 2020-12-22 18:15

Suppose I have a Unix shell variable as below

variable=abc,def,ghij

I want to extract all the values (abc, def an

8条回答
  •  死守一世寂寞
    2020-12-22 18:50

    Here's my pure bash solution that doesn't change IFS, and can take in a custom regex delimiter.

    loop_custom_delimited() {
        local list=$1
        local delimiter=$2
        local item
        if [[ $delimiter != ' ' ]]; then
            list=$(echo $list | sed 's/ /'`echo -e "\010"`'/g' | sed -E "s/$delimiter/ /g")
        fi
        for item in $list; do
            item=$(echo $item | sed 's/'`echo -e "\010"`'/ /g')
            echo "$item"
        done
    }
    

提交回复
热议问题