1

I have a file containing records. The record format is as follows:

Record: XXXXXX [
{variable number of lines and content}
]

At some point within the record, there may be a string that begins with

Start to do this thing

I would like to extract the Record number and the line within the record that matches the word `Start'

Presently I am using

egrep "Record|Start" inputfile.txt >> outputfile.txt

but I must then remove manually the matched Record lines which to not have Start matched. Ideally I would like this to be done in a single step. I would appreciate any suggestions.

1

Using your example file, repeated three times in a row with modifications:

Record: XXXXXX [
{variable number of lines and content}
Start to do this thing
]
Record: YYYYYY [
{variable number of lines and content}
Stop doing this thing
]
Record: ZZZZZZ [
{variable number of lines and content}
Start again
]

Then:

$ awk '/^Record:/ { r = $2 } /^Start/ { print r ":", $0 }' file
XXXXXX: Start to do this thing
ZZZZZZ: Start again

We simply pick up the record number/label as soon as we see a line starting with Record: and save it in the variable r. Then, as we find a line starting with Start we print whatever record label we've found and the line.

If the line doesn't start with Start, you may have to change the regular expression from /^Start/ to /^ *Start/ which will allow any number of spaces between the word and the start of the line.

This will fail if there are other things in the file between the records that matches Start.

  • Thank you. While both answers provided so far have worked, I am choosing this as the correct one since it is easier for me to understand how it works. – Awk-Ward Admin Sep 27 '17 at 16:32
2

Awk solution:

Sample input.txt file:

Record: 111111 [
text
test
Start to do this thing
text
]
Record: 222222 [
{variable number of lines and content}
]
Record: 333333 [
text
text
text
Start to do another thing
text
]

The job:

awk '/^Record: .*\[$/{ f=1; n=$2 }/^\]/{f=0}f && /^Start/{ print n, $0 }' input.txt

The output:

111111 Start to do this thing
333333 Start to do another thing

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.