BestCoderEver
BestCoderEver

Reputation: 567

splitting bash string by delimiter (last line with delimiter) into array

I'm having a hard time splitting a string like this:

444,555,text with, separator

into this:

444
555
text with, separator

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

Upvotes: 0

Views: 70

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

sed editor allows replacing the number th match of the regexp(i.e. the k-th occurence of the string within a line):

str="444,555,text with, separator"
sed 's/,/\n/1; s/,/\n/1' <<< $str

The output:

444
555
text with, separator

s/,/\n/1 - 1 here is a number flag which points to the first occurrence of , to replace with \n

The following will give the same result(implying the first match on each substitution):

sed 's/,/\n/; s/,/\n/' <<< $str

Two consecutive substitutions will give 3 lines(chunks)

Upvotes: 1

Cyrus
Cyrus

Reputation: 88646

With bash and array:

s='444,555,text with, separator'
IFS=, read -r a b c <<< "$s"
array=("$a" "$b" "$c")
declare -p array

Output:

declare -a array='([0]="444" [1]="555" [2]="text with, separator")'

Upvotes: 2

cmks
cmks

Reputation: 537

echo "444,555,text with, separator" | sed  "s/\([0-9]*\),\([0-9]*\),\(.*\)/\1\n\2\n\3/"

Output:

444
555
text with, separator

Upvotes: 0

Related Questions