直到找到下一个标题

直到找到下一个标题

本文介绍了Bash将标题信息附加到文件的每一行,直到找到下一个标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数据标题信息和数据条目的文件。每个标题都会有所不同,我需要将每个标题的信息添加到文件的每一行,直到遇到下一个标题。例如:
$ b $
Header 1,head1_info
date1,data1
date1,data2
Header 2,head2_info
date3,data5
data4,data6



我想这个文件被附加到:

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

我试着将grep分配给变量,但我不知道如何使它从下一个变为下一个,一旦遇到Header 2 ,我也一直在试验sed和awk,但我无法让他们做我想要的。任何指导将不胜感激。

解决方案

这可能适用于您(GNU sed):

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

在遇到标题行时,将其存储在保留空间中对于所有其他行,将保留空间附加到模式空间,并使用反向引用替换所需的信息。


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.

解决方案

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.

这篇关于Bash将标题信息附加到文件的每一行,直到找到下一个标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:12