2

I am looking for a way to iterate through fixed format text files and looking for a specific character in one to many specific character positions, including the first character position, within any line of data in the file. If any of those positions meet the character criteria, I want to output that record/line. Anyone have a grep or awk command that would do this? For example, if I am looking for an asterisk (*) in position 5 or 10 or 25 of file X, how would that be done in awk or grep? Example of file

     cat test.txt
    *   *    *
    *   X    *
    *   *    Y
    *   X    Y
0

3 Answers 3

0
grep '^\(.\{4\}\|.\{24\}\)\*' X

Find all lines if file X containing an asterisk (quoted because otherwise in a regular expression it means zero or more of the preceding atom) preceded by 4 or 24 characters from the beginning of the line.

1
  • THANKS !!! This works very well with my test file with the exception of finding a * at position 1 in the record. cat test.txt * * * * X * * * Y * X Y
    – user203333
    Dec 1, 2016 at 15:35
0

Probably the following awk line will help you understand it better

printf '%s\n' "foo bar *" foo "more foo * more * foo and baz" "another foo bar foo" | awk '{for (i=1;i<=NF;i++) if ($i=="*") print $i " appears in field: " i}'

Just as simple as iterating through fields, matching the field with the pattern and printing it out

0

With at least gawk and mawk, you can treat each character as a field by setting an empty field separator. So for example you can do

gawk -F '' '$5 == "*" || $10 == "*"' test.txt

which causes matching records (lines) to be printed using the default print rule.

A similar trick in perl (note that fields are zero-indexed)

perl -F'' -ane 'print if $F[4] eq "*" || $F[9] eq "*"' test.txt
1
  • Thanks very much for this assistance! Per chance, how would the gawk command be modified to use a starting character position and length to, say, find a string of spaces? for example, if I am looking for 5 spaces starting at position 5 and then 5 spaces starting at position 10? Same type of file, fixed length, no delimiters.
    – user203333
    Dec 1, 2016 at 21:47

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .