将列表拆分为多个列

huangapple go评论55阅读模式
英文:

splitting a list into multiple columns

问题

我有一个文件,其中有两列。第一列包含逗号分隔的值列表,第二列包含单个值列表。我想要将文件拆分,使第一列(每个逗号分隔的值)位于自己的行上,而第二列与第一列中的每个对应值一起。所以这是一个示例:

foo,boo,zoo   10

我希望它看起来像这样:

foo 10
boo 10
zoo 10

拆分逗号分隔的第一列很简单,我在于如何将第二列添加到每行中有困难。

感谢任何帮助。

英文:

I have a file that has two columns. the first column has a comma separated list of values, and the 2nd column has a single list of values. I would like to split the file up so the first column (each comma separated value) is on it's own line, and the 2nd column is with each corresponding value in the first column. so here is an example:

> foo,boo,zoo 10

I would like this to look like this:

foo 10

boo 10

zoo 10

splitting the comma first column is simple, I'm struggling with adding the 2nd column to each line.

Thanks for any help

答案1

得分: 0

使用awk,首先将字段分隔符设置为一个空格。然后将第一列拆分为名为'a'的数组。循环遍历每个元素,打印它,然后跟随第二列。

$ awk 'BEGIN{FS=OFS=" "} {n=split($1,a,","); for (i=1; i<=n; i++) print a[i], $2}' file.txt
foo 10
boo 10
zoo 10
英文:

Using awk, first set the field separator to a space. Then split the first column into an array named 'a'. Loop through each element, printing it followed by the second column.

$ awk &#39;BEGIN{FS=OFS=&quot; &quot;} {n=split($1,a,&quot;,&quot;); for (i=1; i&lt;=n; i++) print a[i], $2}&#39; file.txt
foo 10
boo 10
zoo 10

huangapple
  • 本文由 发表于 2023年3月7日 21:54:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定