doujia2090 2016-07-20 17:13
浏览 53

在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.

  • 写回答

1条回答 默认 最新

  • dongxian0421 2016-07-20 19:30
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试