Hi ,
Im new to uxin environment and shell scripting....
please help me with the code for the following scenario.....
file 1 contains the following fields
abc 200 rupee IND
cdf 400 dollar USA
efg 300 euro GER
hij 600 pound ENG
file 2
SBI abc 321 dollar CANAD
kvr mnd 345 pound FRANC
axs efg 879 euro RUSSIA
if field 1 of file1 matches field 2 of file2 then complete row of filed2 in file should be displayed.
output file:
SBI abc 321 dollar CANAD
axs efg 879 euro RUSSIA
Can someone help on this ....
awk 'NR==FNR{a[$1]++;next}a[$2]' file1 file2
thanks for the reply...
im getting the below error ..
$ awk 'NR==FNR{a[$1]++;next}a[$2]' f1.dat_old f2.dat_old
awk: syntax error near line 1
awk: bailing out near line 1
please let me know how to resolve.
thanks
Shivaji...
On Solaris use /usr/xpg4/bin/awk rather than awk
--
@pravin27
It is better to use
$2 in a
instead of
a[$2]
Because otherwise awk will create a new element a[$2]
for every line in the second file.
would you please explain the login in the syntax "
{a[$1]++;next}a[$2]
"
thanks
Shivaji
drl
April 13, 2013, 8:43am
7
Hi.
Assuming that the files are standardized to have fields separated by single spaces, then here are 2 alternate solutions:
#!/usr/bin/env bash
# @(#) s1 Demonstrate extraction by matching fields.
# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C cut fgrep join
FILES="data?"
pl " Input data file $FILES:"
head $FILES
pl " Results, grep:"
fgrep -f <(cut -f1 -d" " data1) data2
pl " Results, join:"
sort -t " " --key=1,1 data1 > f1
sort -t " " --key=2,2 data2 > f2
join -1 1 -2 2 -t " " -o 2.1,2.2,2.3,2.4,2.5 f1 f2
rm -f f1 f2
exit 0
prodiucing:
% ./s1
Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution : Debian GNU/Linux 5.0.8 (lenny)
bash GNU bash 3.2.39
cut (GNU coreutils) 6.10
fgrep GNU grep 2.5.3
join (GNU coreutils) 6.10
-----
Input data file data?:
==> data1 <==
abc 200 rupee IND
cdf 400 dollar USA
efg 300 euro GER
hij 600 pound ENG
==> data2 <==
SBI abc 321 dollar CANAD
kvr mnd 345 pound FRANC
axs efg 879 euro RUSSIA
-----
Results, grep:
SBI abc 321 dollar CANAD
axs efg 879 euro RUSSIA
-----
Results, join:
SBI abc 321 dollar CANAD
axs efg 879 euro RUSSIA
See man pages for details.
Best wishes ... cheers, drl