Bash将以逗号分隔的单列转换为多行字符串 [英] Bash turning single comma-separated column into multi-line string

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

问题描述

在我的输入文件中,各列用制表符分隔,每列内部的值用逗号分隔.

In my input file, columns are tab-separated, and the values inside each column are comma-separated.

我要打印第一列,并用逗号分隔第二列的值.

I want to print the first column with each comma separated value from the second.

Mary,Tom,David   cat,dog
Kevin   bird,rabbit
John    cat,bird
...

对于第二列中的每个记录(例如cat,dog),我想拆分 记录到[cat,dog]的数组中,并对照 第一栏.提供输出(仅用于此行)

for each record in the second column ( eg cat,dog ) i want to split record into array of [ cat, dog ] and cross print this against the first column. giving output ( just for this line )

Mary,Tom,David   cat
Mary,Tom,David   dog

整个文件的输出应为:

Mary,Tom,David   cat
Mary,Tom,David   dog
Kevin   bird
Kevin   rabbit
John    cat
John    bird
...

有人建议我要使用awk还是sed? 谢谢

any suggest if i want to use awk or sed? Thanks

推荐答案

使用awk

awk '{split($2,a,",");for(i in a)print $1"\t"a[i]}' file

将第二列分割为逗号,然后为每个分割值打印第一列和该值

Splits the second column on commas and then for each split value, print the first column and that value

也在sed

sed ':1;s/\(\([^\n]*\t\)[^\n]*\),\{1,\}/\1\n\2/;t1' file

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆