簡體   English   中英

bash,將兩個逗號分隔的變量值合並為單個變量

[英]bash, merge two comma separated variables values to single variable

我有兩個逗號分隔的變量,如下所示。 在特定條件下,我需要將兩個變量合並為一個變量。 有點困惑,不確定 bash 是否可行

輸入

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

預計 output

OUT=abc_one,def_two,ijk_three 

這是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"

使用bash命令替換、進程替換、參數擴展和paste實用程序:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM