在csv中查找字符串并添加到每一行

在csv中查找字符串并添加到每一行

问题描述:

I have a csv file I fetch from an API and want to load into a MySQL table, I am unsure what to search for to deal with the unusual nature of the file.

CSV looks something like:

meta data
Class 1
1,2,3
5,9,7
Class 2
2,5,4
6,5,4
Class 3
8,4,3
7,8,8

I would like the output to be something I can load more easily:

Class 1,1,2,3
Class 1,5,9,7
Class 2,2,5,4
Class 2,6,5,4
Class 3,8,4,3
Class 3,7,8,8

I'm used to API's returning json's and looping through it in PHP to load the data. This API only has a csv option - the classes always come through in the same order, so i'm thinking maybe a do until loop to append the first value and just repeating it after it runs into the next line which contains 'Class' then rinse and repeat. Not sure if there is an easier way to go about it.

我有一个csv文件,我从API获取并想加载到MySQL表中,我不确定该怎么做 搜索以处理文件的异常性质。 p>

CSV类似于: p>

 元数据
Class 1 
1,  2,3 
5,9,7 
第2类
2,5,4 
6,5,4 
第3类
8,4,3 
7,8,8 
  code>  pre> \  n 
 

我希望输出能够更轻松地加载: p>

  Class 1,1,2,3 
Class 1,5,9,  7 
类2,2,5,4 
类别2,6,5,4 
类别3,8,4,3 
类别3,7,8,8 
  code>  pre> 
 \  n 

我习惯于API返回json并在PHP中循环它以加载数据。 这个API只有一个csv选项 - 类总是以相同的顺序出现,所以我想可能是一个直到循环才能追加第一个值并在它运行到包含'Class'的下一行之后重复它 冲洗并重复。 不确定是否有更简单的方法。 p> div>

With sed :

$ sed '/^Class/{h;d};/^Class/!{G;s/\(.*\)
\(.*\)/\2,\1/g}' file.csv
Class 1,1,2,3
Class 1,5,9,7
Class 2,2,5,4
Class 2,6,5,4
Class 3,8,4,3
Class 3,7,8,8

Use the -i option to edit the file in place:

sed -i '/^Class/{h;d};/^Class/!{G;s/\(.*\)
\(.*\)/\2,\1/g}' file.csv