简体   繁体   中英

copy value from a line to another line with condition using awk

first thanks to all for all i learned here.

this is my input csv :

TYPEµREFµCOLORµ
PRODUCTµ354µblueµ
MODELµ354µµ
MODELµ354µµ
PRODUCTµ253µgreenµ
MODELµ253µµ
MODELµ253µµ

the separator is {FS="µ";OFS="µ"}

what i have :

  • each PRODUCT line contain a value in COLOR column.
  • each MODEL line contain a empty COLOR column.

What i want :

  • i want to copy Color string from each PRODUCT line in color string of each MODEL line with the same REF as PRODUCT.
  • (REF is the Sync KEY linking PRODUCT and MODEL.)

Result i want :

TYPEµREFµCOLORµ
PRODUCTµ354µblueµ
MODELµ354µblueµ
MODELµ354µblueµ
PRODUCTµ253µgreenµ
MODELµ253µgreenµ
MODELµ253µgreenµ

I hope i was clear....

i tried to work with if and -va long time ....

Thanks by advance.

PéPé.

You can use this awk :

awk -F'µ' '$1 ~ /^PRODUCT/{color=$3} $1 ~ /^MODEL/{$3=color}1' OFS='µ' file

Explanation:

  • $1 ~ /^PRODUCT/ - Matching a column against PRODUCT .
  • color=$3 - Storing a $3 value.
  • $1 ~ /^MODEL/ - Matching a column against 'MODEL'.
  • $3=color - Assigning a value to $3 .

using a memory of all product

awk 'BEGIN { OFS = FS = "µ"}
   {
   if ($1 ~ /^PRODUCT/) Prod[ $2] = $3
    else if (Prod[ $2] !~ /^$/) $3 = Prod[ $2]
   print
   }' YourFile

assuming model are associate only to header product

awk 'BEGIN { OFS = FS = "µ"}
   {
   if ($1 ~ /^PRODUCT/){ Ref=$2; Color = $3 }
    else if ( Ref == $2 && Color !~ /^$/) $3 = Color
   print
   }' YourFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM