Home > Blockchain >  bash, merge two comma separated variables values to single variable
bash, merge two comma separated variables values to single variable

Time:10-02

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 

CodePudding user response:

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"

CodePudding user response:

Using bash here-strings, process substitution and, paste and tr utilities:

OUT=$(paste -d_ <(tr , '\n' <<<"$SBI") <(tr , '\n' <<<"$MEM") | tr '\n' ,)
OUT=${OUT%,}
echo "OUT=$OUT"

CodePudding user response:

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%,}"
  • Related