-5

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

OUT=abc_one,def_two,ijk_three 
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
upkar
  • 143
  • 8
  • 2
    please add your attempted code – anubhava Oct 01 '22 at 18:16
  • 2
    Note that all-caps names are used for variables that have special meaning for the shell or operating system; names you define yourself should have at least one lower-case character. See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html -- the convention applies to regular variables as well as environment variables because they share a namespace (setting a shell variable overwrites any like-named environment variable). – Charles Duffy Oct 01 '22 at 18:19

3 Answers3

2

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"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
1

Using bash command substitution, process substitution, parameter expansion and, paste utility:

OUT=$(paste -d_ <(echo "${SBI//,/$'\n'}") <(echo "${MEM//,/$'\n'}"))
OUT=${OUT//$'\n'/,}
echo "OUT=$OUT"
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
0

With sh.

#!/bin/sh

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

out=$(
  while [ -n "$SBI" ] && [ -n "$MEM" ]; do
    sbi_first="${SBI%%,*}"
    sbi_rest="${SBI#*"$sbi_first"}"
    mem_first="${MEM%%,*}"
    mem_rest="${MEM#*"$mem_first"}"
    SBI="${sbi_rest#,}"
    MEM="${mem_rest#,}"
    printf '%s_%s,' "$sbi_first" "$mem_first"
  done
)

echo "${out%,}"

With bash

#!/usr/bin/env bash

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

while IFS= read -ru3 str0; do
  IFS= read -r str1
  out+="${str0}_$str1,"
done 3<<< "${SBI//,/$'\n'}" <<<"${MEM//,/$'\n'}"

echo "${out%,}"
Jetchisel
  • 7,493
  • 2
  • 19
  • 18