本文介绍了在Bash中将多行字符串转换为单个逗号分隔的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式:

host1,app1
host1,app2
host1,app3
host2,app4
host2,app5
host2,app6
host3,app1
host4... and so on.

我需要这样的格式:

host1;app1,app2,app3
host2;app4,app5,app6

我对此感到厌倦:awk -vORS=, '{ print $2 }' data | sed 's/,$/\n/' 它给了我这个:

I have tired this: awk -vORS=, '{ print $2 }' data | sed 's/,$/\n/' and it gives me this:

app1,app2,app3,没有主机在前.

我不想显示重复的内容.

I do not want to show duplicates.

我不想要这个:

host1;app1,app1,app1,app1...
host2;app1,app1,app1,app1...

我想要这种格式:

host1;app1,app2,app3
host2;app2,app3,app4
host3;app2;app3

推荐答案

$ awk '
    BEGIN { FS=","; ORS="" }
    $1!=prev { print ors $1; prev=$1; ors=RS; OFS=";" }
    { print OFS $2; OFS=FS }
    END { print ors }
' file
host1;app1,app2,app3
host2;app4,app5,app6
host3;app1

这篇关于在Bash中将多行字符串转换为单个逗号分隔的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:24