Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash, merge two comma separated variables values to single variable

I have two commas separate variables like below. on a certain condition, I need to merge two variables into a single. Bit confused and unsure if is it possible in bash

Input

SBI=abc,def,ijk
MEM=one,two,three

Expected output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OUT=abc_one,def_two,ijk_three 

>Solution :

This is a simple extension of Iterate over two arrays simultaneously in bash, combined with How to split a string into an array in bash.

IFS=, read -ra sbi_arr <<<"$SBI" # convert SBI string to an array
IFS=, read -ra mem_arr <<<"$MEM" # convert MEM string to an array

out=                             # initialize output variable
for idx in "${!sbi_arr[@]}"; do  # iterate by indices
  out+="${sbi_arr[$idx]}_${mem_arr[$idx]}," # append to output
done
out=${out%,}                     # strip trailing comma from output

echo "Output is: $out"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading