Using awk, extract the first and last numbers between two strings in a column in a text file, and difference those?

Viewed 104

I have a text file that looks similar to below.

Code 1 (3)
5     10     10
6     10     10
7     10     10
Code 2 (2)
9     11     11
10     8      8
Code 3 (1)
12    10      9
Code 4 (2)
14     8     10
15     8     10

I am only interested in the first and last numbers, in the first column. I would like to extract the first, last, and difference (1+last-first) to a new text file with a column for each first, last, and difference. The result should look like below. Technically, the difference column could be the number between the parentheses, as this number would always be the 1+difference between the last and first numbers between each string. Note, the last row in the input text file does not have a string below it.

5     7     3
9    10     2
12   12     1
14   15     2

Trying awk '/Code/{flag=1;next}/Code/{flag=0}flag' gives me all the lines and columns between each string. Trying awk '$1 ~ /Code/{flag=1;next},$1 ~ 1 /Code/{flag=0}flag' results in a syntax error at ,.

1 Answers

You may use this awk:

awk -v OFS='\t' '/^Code/ {
   if (NR > 1)
      print first, prev, (prev-first+1)
   first = prev = ""
   next
}
(first == "") {
   first = $1
}
{
   prev = $1
}
END {
   print first, prev, (prev-first+1)
}' file

5   7   3
9   10  2
12  12  1
14  15  2
Related