2

File1 has data as below , is the field separator

1,T_EXIT,9053.0,10325.0,, ,  
2,V_TURN,120.0,11334.0,, , 
3,Q_ENTRY,122.0,190.0,, , 
4,Q_ENTRY_RUN,130.0,569.0,, ,

File2 has data

VDS SYNC
Dig T_EXIT OPEN
Ana Q_ENTRY CLOSE
Dig CORE_T 

I want to compare column2 of file2 with column2 of file1 and if EXCAT MATCH is there I want to copy column3 from file2 in column6 and column7 in file1

I want output as:

1,T_EXIT,9053.0,10325.0,,OPEN,OPEN 
2,V_TURN,120.0,11334.0,, , 
3,Q_ENTRY,122.0,190.0,,CLOSE,CLOSE
4,Q_ENTRY_RUN,130.0,569.0,, ,

I tried below code, but I could not get desired output. What correction needed.

awk 'NR==FNR{A[$2]=$3;next}$2 in A{$6=A[$2]}1' file2 file1 > test

2 Answers 2

4

Really all you're missing is the change of input and output field separators between the files:

$ awk 'NR==FNR{A[$2]=$3;next} $2 in A{$7=$6=A[$2]}1' file2 FS=, OFS=, file1
1,T_EXIT,9053.0,10325.0,,OPEN,OPEN
2,V_TURN,120.0,11334.0,, , 
3,Q_ENTRY,122.0,190.0,,CLOSE,CLOSE
4,Q_ENTRY_RUN,130.0,569.0,, ,
0
0

Awk seems like thewrong tool here. It also sounds like a homework problem. I would use:

tr ' ' ',' <File2 >File3
join -t ',' -1 2 -2 2 File1 File3
3
  • I do with awk, and it works for matching and adding values to columns. In my code I am missing something which need to know
    – Shreya
    Feb 28, 2023 at 15:55
  • 3
    join requires the input to be sorted on the join keys so you'd have to add a couple of calls to sort too if you don't want to just use one awk command. Maybe something like join -t ',' -1 2 -2 2 <(sort -t ',' -k2,2 File1) <(tr ' ' ',' <File2 | sort -t ',' -k2,2) would work. FWIW I find the one call to awk simpler+clearer than multiple commands with pipes and process substitution (or temp files) but that may be just based on my own experience.
    – Ed Morton
    Feb 28, 2023 at 16:46
  • 1
    Actually, I think you'd need yet another step for this to modify the 6th and 7th fields of File1 rather than adding fields and I'm not sure what it'd do with lines that don't match across the 2 files. It'd be interesting to see the output it produces from the OPs sample input.
    – Ed Morton
    Feb 28, 2023 at 17:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .