Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String/field compare and append

Status
Not open for further replies.

stefmit

MIS
Sep 14, 1998
2
US
Getting my feet wet ;)
I have two files - one (file1) formatted like this:

aa:bb:cc XXXXXX
dd:ee:ff YYYYYYYY
gg:hh:ii ZZZ
<and many other similar lines>

and the other (file2) formatted like this:

dd:ee:ff:mm:nn:eek:o 1.2.3.4
<and many other similar lines>

I need to find the dd:ee:ff in the forst file, corresponding to the first three groupings in file2, line by line, than replace in file2 the grouping dd:ee:ff with YYYYYYYY ...

I have not done Perl in many years, but this is what I would have to resort to, if not able to learn awk :(

TIA,
Stef
 
A starting point:
awk '
FNR==NR{a[$1]=$2;next}
{b=$0;k=substr($1,1,8);if(k in a)b=a[k]substr($0,9);print b}
' file1 file2 > newfile2

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thank you - great! Now I will have to go through it and understand it :)
 
[tt]
# Before reading any files, set the field-separator.
BEGIN { FS=":" }

# Are we reading the first file? NR is the total number
# of records (lines) read so far; FNR is the number of
# records read from current file; the two variables are
# equal ONLY when we're still in the first file.
FNR==NR {
# Yes; remember key and value.
# First make array temp contain the blank-separated
# parts of the current line ($0).
split( $0, temp, / +/ )
a[ temp[1] ] = temp[2]
# Immediately read next line.
next
}

# We have a line from the second file.
{ # FS was set to ":", so if we've just read
# "dd:ee:ff:mm:nn:eek:o 1.2.3.4" then
# $1 is "dd", $2 is "ee", etc.
key = $1 ":" $2 ":" $3
if ( key in a )
key = a[key]
print key ":" $4 ":" $5 ":" $6
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top