Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending string to awk output

Tags:

awk

I have a text file with following content

data
void
void
void
1
2
3
end
6
7
8
9
data
void
void
void
4
5
6
end
4
5
8
9

I wanted to extract lines between strings 'data' and 'end' and have achieved it with the following awk one-liner

awk '/data/,/end/{i++} /end/{i=0} i>4' filename

The output is:

1
2
3
4
5
6

Now I wanted the number of times the data point appears to be appended before each block. Something like this:

3

1
2
3

3

4
5
6

Is it possible to achieve this by awk?

like image 339
JohnP Avatar asked Jul 17 '26 13:07

JohnP


1 Answers

You can do it fairly easily if you just count lines that are comprised of digits between the occurrence of data and end and store the values in an array indexed by the count. Then when end is reached, output the count and then the values stored in the array before resetting the count and the flag that indicates you are between a data and end, e.g.

awk '
  /data/ { between = 1 } 
  between==1 && $1~/^[[:digit:]]+$/ { a[++n] = $1 } 
  /end/ {
    printf "\n%d\n\n", n
    for (i = 1; i <= n; i++)
      print a[i]
    between = n = 0
  }
' file

(note: if you can have two or more data records without an end that follows each data record, you will need to add a test or handle that as needed. That is left to you.)

Example Use/Output

With your input in file, you would get:


3

1
2
3

3

4
5
6

Let me know if you have further questions.

like image 115
David C. Rankin Avatar answered Jul 20 '26 18:07

David C. Rankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!