I have a 17k lines-long file F1 with 8 fields per line formatted as follows:

id1 field2 field3 field4 field5 field6 field7 field8
id2 field2 field3 field4 field5 field6 field7 field8

The second file F2 content unfolds in a single field per line (one column)


The lines from F2 should be replaced with the lines from F1 if there is a match. Thought the weird while loop below could work but, needless to say, it returns all the lines from F2 per change made. Or probably Bash may have other magical tools that could do the trick, perhaps?

while read id1 id2 id3 id4 id5; do
        while read ID; do
                if [[ $ID == "$id1" ]]; then
                        sed "s/$ID/$id1 $id2 $id5 $id4/" F2 && break
        done < F2
done < F1

This is a job for

awk 'NR == FNR {line[$1] = $0; next} $1 in line {$0 = line[$1]} 1' F1 F2 
  1. NR == FNR {line[$1] = $0; next} -- while reading F1, store each line keyed by the first field
  2. $1 in line {$0 = line[$1]} -- we're reading F2 now: if the first field is in the line array, substitute the array value as the current record.
  3. 1 -- print the current record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.