Map a string in a the middle of a record

Hi Folks!

I hope you can help me figure this out. I need to print a record which contains the contents of a config file. The contents of the config file should be found within the 21st and the 30th position of the fixed width reference file.

Config File:

aaaa
bbbb
cccc

Reference File:

123456789           bbbb      234545
123454567           cccc      23452  
1234567890sas       dddd      1234
124345677           bbbb      123445

Expected Output:

123456789           bbbb      234545
123454567           cccc      23452  
124345677           bbbb      123445

I hope the gurus can help me
~kokoro

$> cat /tmp/a.txt
123456789           bbbb      234545
123454567           cccc      23452
1234567890sas       dddd      1234
124345677           bbbb      123445

$> cat /tmp/b.txt
aaaa
bbbb
cccc

$> fgrep -w -f /tmp/b.txt /tmp/a.txt
123456789           bbbb      234545
123454567           cccc      23452
124345677           bbbb      123445
awk 'BEGIN{
FIELDWIDTHS = "20 10 100"}
NR == FNR {a[$1]; next}
{t = $2;
gsub(" ", "", t);
if(t in a)
  print}' conf ref

If your reference file always looks like this (that is, the fields are surrounded by ample whitespace AND the search patterns will not appear somewhere else on the line), itkamarajs solution is probably the easiest and fastest.

If the file could contain lines like this:

123456789           bbbb      234545
123454very_long_linecccc      23452  

where it is not possible to match for a word and the search pattern is distinguishable only by the position on the line you will have to do a bit more, for instance a shell loop:

#! /bin/ksh
typeset PATTERN=""
cat /path/to/config.file |\
while read PATTERN ; do
     grep '^.\{20\}'"${PATTERN}" /path/to/reference.file
done
exit 0

This will "anchor" the pattern to character position 21 in the line by searching for "20 characters followed by $PATTERN".

If the search patterns contain regexp metacharacters (like "", ".", etc.) you might have to take evn more precautions by escaping these (precede them with a backslash, i.e. "" -> "\*").

Taking all these precautions will not hurt, even if they are unnecessary, but they might slow down the process, soanalyze your data carefully if they are necessary or not.

I hope this helps.

bakunin