2

How can I search lines in a text file for a pattern between two positions and print the entire row where that pattern is found? I am working with fixed-width files. I understand how to supply a list of lengths for each field to awk, but I am only interested in searching a single field for the pattern. Is there a simpler solution that does not involve specifying the length for each field?

Here is a single line of text from the file. How can I find all lines that have 'Cook Co. IL' between positions 18 and 57 and not elsewhere in the line?

17 031 1602 1600 Cook Co. IL                              047 011 9999 9999 Bradley Co. TN                                16
3

awk solution:

awk 'substr($0,18,57-18)~/Cook Co\. IL/' file

substr(string, start [, length ])
Return a length-character-long substring of string, starting at character number start.

2

It's not that hard to specify field widths, given that you only want to consider the line as three fields (0-17, 18-57, 58+):

awk -v FIELDWIDTHS="17 40"  -e '$2 ~ /Cook Co\. IL/'
0
sed -e 'h; s/./&\n/57; /^.\{17\}.*Cook Co[.] IL.*\n/!d; g' yourfile

Mark out the right-boundary and constrain using ^ the left boundary. Within this region look for the regex. If found, print the hold which has orig. line.

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.