Linux Shell脚本:以指定的方式从字符串中提取值

时间:2017-01-20 08:21:07

标签: linux shell

我有一个变量包含如下值:

USER1:USER2,USER3:USER4,USER5:USER6

我想提取像USER1,USER3,USER5

这样的值

例如:

VALUE = USER1:USER2,USER3:USER4,USER5:USER6

echo如何像这样提取

USER1,USER3,USER5

1 个答案:

答案 0 :(得分:0)

#!/bin/bash

string=USER1:USER2,USER3:USER4,USER5:USER6
IFS=', ' read -r -a array <<< "$string"
output=

for kv in ${array[@]}; do
    key=$(echo $kv | cut -d':' -f1)
    output="$output,$key"
done

output=$(echo $output | cut -c 2-)
echo $output