简体   繁体   English

bash,将两个逗号分隔的变量值合并为单个变量

[英]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有点困惑,不确定 bash 是否可行

Input输入

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

Expected output预计 output

OUT=abc_one,def_two,ijk_three 

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 .这是bash 中同时迭代两个 arrays的简单扩展,结合 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"

Using bash command substitution, process substitution, parameter expansion and, paste utility:使用bash命令替换、进程替换、参数扩展和paste实用程序:

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

With sh .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 bashbash

#!/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%,}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM