采用多个标题(行匹配条件)并转换为列

Tho*_*ine 1 bash perl awk command-line sed

您好我有一个文件,其中包含多个标题,我需要将其转换为列值.该文件如下所示:

Day1
1,Smith,London
2,Bruce,Seattle
5,Will,Dallas
Day2
1,Mike,Frisco
4,James,LA
Run Code Online (Sandbox Code Playgroud)

我想文件最终看起来像这样:

Day1,1,Smith,London
Day1,2,Bruce,Seattle
Day1,5,Will,Dallas
Day2,1,Mike,Frisco
Day2,4,James,LA
Run Code Online (Sandbox Code Playgroud)

该文件在名称之前没有序列号,并且在"日"标题之后没有相同数量的记录.有没有人对如何使用命令行完成此任务有任何想法?

123*_*123 6

在awk

awk -F, 'NF==1{a=$0;next}{print a","$0}' file
Run Code Online (Sandbox Code Playgroud)

检查字段数是否为1,如果是,则设置变量并跳过下一个块.

对于没有1个字段的每一行,它会打印保存的变量和行

并在sed

sed -n '/,/!{h};/,/{x;G;s/\n/,/;p;s/,.*//;x}' file
Run Code Online (Sandbox Code Playgroud)

为MrBones狂野骑行打破了局面.

sed -n '

        /,/!{h};       // If the line does not contain a comma overwrite buffer with line

       /,/{            // If the line contains a comma, do everything inside the brackets
           x;          // Exchange the line for the held in buffer
           G;          // Append buffer to line
           s/\n/,/;    // Replace the newline with a comma
           p;          // Print the line
           s/,.*//;    // Remove everything after the first comma
           x           // exchange line for hold buffer to put title back in buffer for the next line.
          }' file      // The file you are using
Run Code Online (Sandbox Code Playgroud)

从本质上讲,它可以在不使用,标题的情况下保存行.然后,如果它不是标题,它将使用保存的标题切换当前行,并将现在切换的行追加到标题的末尾.因为它附加了换行符,然后下一个语句用逗号替换它.然后打印该行.NExt恢复标题,删除后的所有内容,并将其交换回缓冲区,为下一行做好准备.