Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I got a file that contains the key only. Records are unique.
I want to take that key and go against multiple files and extract record from them. Note, the files that I am trying to match may contain my key in a fixed position. Say, for file A the key is from 12 to 20 and for file B it is in 0 to 9.
I know I can use grep agains the key file for matching some thing like:
fgrep -f record_key data_out >data_updatedbut how do I go against maching those particular fields. Also is there an easy way to go against both the files same time ?
Many thnaks again!!!Report Offensive Follow Up For Removal

This solution loads your keys into an array, then processes two files against it. It checks which FILENAME is being processed to locate the key.
awk 'BEGIN \
{while ((getline < "mykeys") > 0)
keyfile[$1] = 1
}
{if (FILENAME == "fileA")
key=substr($0,11,9)
else
key=substr($0,1,10)
if (key in keyfile)
}' fileA fileB

Thanks a lot Jim! This works. Now that I got my key and matches, Instead of printing them, I want to redirect to files in different dir with the same name some thing like:
/new_dir/fileA
/new_dir/fileBNote: Results only should end up on these files. So what do I change instead of "Print" in the above AWK.
Again Thanks a lot!!!

This revised solution outputs to separate files based on the current input file. You do not need to print with append (print >>) because awk keeps all output files opened until either an explicit close or end or program. Use the append only if you actually want to append to existing files.
awk 'BEGIN \
{while ((getline < "mykeys") > 0)
keyfile[$1] = 1
}
{if (FILENAME == "fileA")
{key=substr($0,11,9)
outfile="/new_dir/fileA"}
else
{key=substr($0,1,10)
outfile="/new_dir/fileB"}
if (key in keyfile)
print > outfile
}' fileA fileB

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |