mike
mike

Reputation: 87

Linux/Bash: replace if the same id in table

I have two files:

file 1
Name   Height
Jay    180
Kathy  171
Amy    163
Bill   176
Hellen 157

file 2
Name   Height
Jay    195
Amy    173
Hellen 161

and I want to replace the value in the second column in file 1, if the names (column 1) match in file 2. If names are not matched, then remain unchanged. The result should be:

Name   Height
Jay    195
Kathy  171
Amy    173
Bill   176
Hellen 161

Only Jay, Amy and Hellen's height have changed because their name exist in file 2.

I tried to work this out with for loop plus awk or join, but not very well. In the end I used excel to generate a LONG awk command from file 2 and applied ion file 1, it worked:

awk '{OFS="\t";
if($1~/^Jay$/){$2="195"; print $0;} 
else if($1~/^Amy$/){$2="173"; print $0;} 
else if($1~/^Hellen$/){$2="161"; print $0;} 
}' file 1

In this way, I tried to use for loop to generate:

else if($1~/^   Amy   $/){$2="   173    ";print $0;}  

Above it contains command part1 & name & command part2 & height to replace & command part3. But it is hard to put these command into a variable because it contains special characters like: if, ~, /, $

I am wondering that if there are any simpler way to do it only by command? Thanks!

Charlie

Upvotes: 0

Views: 184

Answers (3)

Matias Barrios
Matias Barrios

Reputation: 5054

This script will do too.

#!/bin/bash

while read name height
do
        printed=0
        printf "$name\t"
        while read subname subheight
        do
                [[ $name == $subname ]] && printf "$subheight\n" && printed=1
                continue
        done <<< "$( tail -n +2 secondary.txt)"
        [[ $printed -eq 0 ]] && printf "$height\n"

done <<< "$( tail -n +2 main.txt)"

Upvotes: 0

karakfa
karakfa

Reputation: 67567

if the order is not important it can be as simple as

$ awk '!a[$1]++' file2 file1

Name   Height
Jay    195
Amy    173
Hellen 161
Kathy  171
Bill   176

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133760

Could you please try following.

awk 'FNR==NR{a[$1]=$2;next} {$0=a[$1]?$1 OFS a[$1]:$0} 1'  file2  file1 | column -t

Output will be as follows.

Name    Height
Jay     195
Kathy   171
Amy     173
Bill    176
Hellen  161

Upvotes: 0

Related Questions