在CSV文件上添加新行

时间:2015-11-02 15:25:26

标签: bash csv

我希望使用bash转换CSV文件,方法是在其中添加新行,具体取决于下面描述的某些条件:

CSV文件结构:

name,id_name,url
Amy,N1,http://google.com
Rob,N2,http://google.com http://other-url.com http://anotherurl.com http://other-again.com
Johh,N3,http://google.com http://anotherurl.com
Jack,N4,http://google.com http://other-url.com
...

我想像这样转换CSV文件:

name,id_name,url
Amy,N1,http://google.com
Rob,N2,http://google.com
Rob,N2,http://other-url.com
Rob,N2,http://anotherurl.com 
Johh,N3,http://google.com
Johh,N3,http://anotherurl.com
Jack,N4,http://google.com 
Jack,N4,http://other-url.com
...

由于

4 个答案:

答案 0 :(得分:1)

只需要拆分最后一个字段,然后打印第一个和第二个字段,然后打印这些切片:

awk 'BEGIN{FS=OFS=","}{n=split($NF,a," "); for (i=1;i<=n;i++) print $1,$2,a[i]}' file

返回:

Amy,N1,http://google.com
Rob,N2,http://google.com
Rob,N2,http://other-url.com
Rob,N2,http://anotherurl.com
Rob,N2,http://other-again.com
Johh,N3,http://google.com
Johh,N3,http://anotherurl.com
Jack,N4,http://google.com
Jack,N4,http://other-url.com

答案 1 :(得分:1)

这个awk应该可以工作:

awk -F '[, ]' -v OFS=, '{for (i=3; i<=NF; i++) print $1, $2, $i}' file
name,id_name,url
Amy,N1,http://google.com
Rob,N2,http://google.com
Rob,N2,http://other-url.com
Rob,N2,http://anotherurl.com
Rob,N2,http://other-again.com
Johh,N3,http://google.com
Johh,N3,http://anotherurl.com
Jack,N4,http://google.com
Jack,N4,http://other-url.com
  • -F '[, ]'将字段分隔符设置为逗号或空格。
  • 然后开始从字段#3开始迭代并将其与前2个字段一起打印。

答案 2 :(得分:0)

使用bash

while IFS=, read name id url; do
  set -f
  for u in $url; do
    echo "$name,$id,$u"
  done
  set +f
done < file
name,id_name,url
Amy,N1,http://google.com
Rob,N2,http://google.com
Rob,N2,http://other-url.com
Rob,N2,http://anotherurl.com
Rob,N2,http://other-again.com
Johh,N3,http://google.com
Johh,N3,http://anotherurl.com
Jack,N4,http://google.com
Jack,N4,http://other-url.com

这不会为url字段为空的任何记录提供支持。

我正在利用shell word-splitting和for循环中的未加引号变量。为了安全起见,我在关闭filename expansion的时候关掉了。{/ p>

答案 3 :(得分:0)

perl -F'[, ]' -lane 'for ($i=2; $i<=$#F; $i++) {print "$F[0],$F[1],$F[$i]"}' file

-a将每一行自动分配到@F数组中 -F'[, ]' autosplit字段分隔符是逗号或空格
$#F@F数组的最后一个元素的索引 perl数组以索引0开头,而awk以1

开头