awk compare column n replace with in one file

hi Friends
need to compare columns in one file where the data looks like below

laptop,IBM
phone,samsung
car,rental
user1,laptop
user2,laptop
user3,phone

want to get output as

laptop,IBM
phone,samsung
car,rental
user1,IBM
user2,IBM
user3,samsung

need to seach $2 in array of $1 and if found print the $2 of the found...
if not print as it is

With assumptions:

awk -F, '$2 in a{$2=a[$2]}{a[$1]=$2}1' OFS=, file
1 Like

Hi

awk -F, 'NR==FNR{a[$1]=$2;next}{$2=a[$2]?a[$2]:$2}1' OFS=,  file file

Guru.

1 Like

thanks for that,i tried all this while to understand the idea. still coudnt

awkishly speaking:

awk -F, '                # set "," as field separator
$2 in a{$2=a[$2]}        # if field 2 is an array a key set field 2 to array a value for field 2 key
{a[$1]=$2}1              # store field 2 in array a value for field 1 key and print line
' OFS=, file             # use "," as output field separator, use file as input
1 Like