Bash Append header information to each line of a f

2019-09-06 06:31发布

I have a file that contains data header information followed by data entries. Each header will be different and I need to add the information from each header onto each line of the file, until the next header get encountered. For instance:

"Header 1","head1_info" date1,data1 date1,data2 "Header 2","head2_info" date3,data5 data4,data6

I want this file to be appended to:

    `"Header 1","head1_info"
    head1_info,date1,data1
    head1_info,date1,data2
    "Header 2","head2_info"
    head2_info,date3,data5
    head2_info,date4,data6`

I've tried assigning grep to variable, but I don't know how to make it change from to the next one, once it encounters "Header 2", I've also been experimenting with sed and awk, but I can't get them to do what I want either. Any guidance would be greatly appreciated.

2条回答
成全新的幸福
2楼-- · 2019-09-06 07:12

This might work for you (GNU sed):

sed -r '/^"/h;//!{G;s/(.*)\n.*"(.*)"/\2,\1/}' file

On encountering a header line store it in the hold space. For all other lines, append the hold space to the pattern space and substitute the required info using back references.

查看更多
别忘想泡老子
3楼-- · 2019-09-06 07:21

Assuming any line which contains a double quote indicates a header line:

awk '/"/{a=$2;gsub("\"","",a); print; next}{print a FS $0}' FS=, input

If there is some other method to determine a header, just change the pattern matched at the start. (This records the value of column 2 from header lines in the variable a. The gsub just strips the double quotes.)

查看更多
登录 后发表回答