Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Split a string by delimiter ignoring spaces

I have string like

name1::1.1.1.1::ps -ax

I want to split the string based on delimiter :: using bash scripting.

The desired output should be an array of 3 elements

("name1" "1.1.1.1" "ps -ax")

without double quotes

I appreciate your help.

like image 521
Appaji Koppula Avatar asked Mar 07 '26 04:03

Appaji Koppula


2 Answers

Assuming there are no :s in the array data, use bash pattern substitution to squeeze the :: to : while assigning the string to $array, then show the whole array, then just element #2:

a="name1::1.1.1.1::ps -ax"
IFS=: array=(${a//::/:}) ; echo ${array[@]} ; echo "${array[2]}" 

Output:

name1 1.1.1.1 ps -ax
ps -ax

But what if there are :s in the array data? Specifically in the third field, (the command), and only in that field. Use read with dummy variables to absorb the extra :: separators:

a="name1::1.1.1.1::parallel echo ::: 1 2 3 ::: a b"
IFS=: read x a y b z <<< "$a"; array=("$x" "$y" "$z"); printf "%s\n" "${array[@]}"

Output:

name1
1.1.1.1
parallel echo ::: 1 2 3 ::: a b
like image 103
agc Avatar answered Mar 08 '26 18:03

agc


The only safe possibility is use a loop:

a='name1::1.1.1.1::ps -ax'
array=()

a+=:: # artificially append the separator
while [[ $a ]]; do
    array+=( "${a%%::*}" )
    a=${a#*::}
done

This will work with any symbol in a (spaces, glob characters, newlines, etc.)

like image 41
gniourf_gniourf Avatar answered Mar 08 '26 19:03

gniourf_gniourf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!