|
Home > Archive > Unix Shell > March 2004 > Lookup and substituting a value..
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Lookup and substituting a value..
|
|
|
| If I have a file like:
XX 12345
YY abcde
ZZ xcvbn
and I have another file that is basically a lookup table:
12345 ttttt
43534 hhhhh
23443 jjjjj
and I want to look up the second columb in the first file, so '12345', and
find its match in the second file, and substitute the corresponding value
into the first file, so end up with:
XX ttttt
YY abcde
ZZ xcvbn
How the heck is that done?!
| |
| joe@invalid.address 2004-03-23, 8:35 pm |
| "kb" <kbesner@hfx.eastlink.ca.nospam> writes:
> If I have a file like:
> XX 12345
> YY abcde
> ZZ xcvbn
>
> and I have another file that is basically a lookup table:
> 12345 ttttt
> 43534 hhhhh
> 23443 jjjjj
>
> and I want to look up the second columb in the first file, so '12345', and
> find its match in the second file, and substitute the corresponding value
> into the first file, so end up with:
> XX ttttt
> YY abcde
> ZZ xcvbn
>
> How the heck is that done?!
Assuming the first file is named dat1 and the second file is dat2,
awk -v F1=dat1 '
BEGIN {
while(getline < F1) {
lookup[$1] = $2
}
}
{
lookup[$1] = $2
}
END {
for(l in lookup)
{
printf("%s = %s\n", l, lookup[l])
}
}' <dat2
Output on my machine is
XX = ttttt
YY = abcde
ZZ = xcvbn
Joe
--
Don't worry, be happy
- Bobby McFerrin
| |
| Ed Morton 2004-03-23, 10:35 pm |
|
kb wrote:
> If I have a file like:
> XX 12345
> YY abcde
> ZZ xcvbn
>
> and I have another file that is basically a lookup table:
> 12345 ttttt
> 43534 hhhhh
> 23443 jjjjj
>
> and I want to look up the second columb in the first file, so '12345', and
> find its match in the second file, and substitute the corresponding value
> into the first file, so end up with:
> XX ttttt
> YY abcde
> ZZ xcvbn
>
> How the heck is that done?!
>
With awk of course ;-):
awk 'NR == FNR {f1s[$2]=""; next}
$1 in f1s { $1 = f1s[$1] }
{ print }' file1 file2
"join" might work too, take a look at it's man page.
Regards,
Ed.
| |
| Ed Morton 2004-03-23, 10:35 pm |
|
Ed Morton wrote:
<snip>
> awk 'NR == FNR {f1s[$2]=""; next}
> $1 in f1s { $1 = f1s[$1] }
> { print }' file1 file2
Oops:
awk 'NR == FNR {f1s[$2]=$1; next}
$1 in f1s { $1 = f1s[$1] }
{ print }' file1 file2
|
|
|
|
|