4

Replacing lines containing a pattern with sed

Thanks to @don_crissti and @Archemar. I reckon my question is not a duplication of the above question.

So here is an example of input. Edit: All sections have values. I've added another complexity to the subheading (I should have done that).

DATA1

NAME: A (X)
12,1
13,2
14,4

NAME: B (X)
21,2
22,3

NAME: C (X)
24,4

The desired output should look like

DATA1

A    12,1
A    13,2
A    14,4

B    21,2
B    22,3

C    24,4
3

It seems that your output separator is 4 spaces, so that's what this example uses - change it to what ever you need, eg for a TAB, OFS="\t"

awk 'NR==1 || NF==0 {print; next}  # main heading and blank lines 
     $1=="NAME:" {name=$2; next}   # section name/header
     {print name, $1}              # data lines
    ' OFS="    " file

Output:

DATA1

A    12,1
A    13,2
A    14,4

B    21,2
B    22,3

C    24,4
  • You can combine the 1st and 3rd conditions: NR==1 || NF==0 {print; next} – glenn jackman Jul 21 '15 at 21:05
  • Thanks @glennjackman, especially for the ==, and the reminder to use the number of fields – Peter.O Jul 21 '15 at 21:12
2

Here's sed. I don't recommend it

sed -n '
    1 {p; n}
    /^[[:blank:]]*$/ {p; n}
    /^NAME: \+/ {s///; h; n}
    {H; g; s/\n/ /; p; s/ .*//; h}
' file

It does just what Peter's awk command does, except sed has only one variable: the hold space.

  • 1
    Since the OP changed the format of the Input data, it needs an additional 's/ .*//; before h; n} (or similar). – Peter.O Jul 22 '15 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.