-1

Hi I am trying to get last same kind of record values with primary key

list.csv

tag1,slate1,flag1,check1,1,2
tag2,slate2,flag2,check2,1,2
tag3,slate3,flag3,check3,1,2
tag1,slate1,flag1,check1,3,4
tag3,slate3,flag3,check3,1,2

here primary key is col1+col2+col3+col4

and I need to insert new record tag1,slate1,flag1,check1,5,6 in this record I need to get last same kind of record[If many record exists I need to get just last same primary key record] [tag1,slate1,flag1,check1,3,4] and fetch and get 3,4 values and make it like below record,

tag1,slate1,flag1,check1,5,6,3,4

I am trying like, but not getting expected output.

awk -F, '!dup[$1,$2,$3,$4]++' list.csv - removing duplicates , but able to fetch expected record


awk -F, '!dup["tag1","slate1","flag1","check1"]++' list.csv

I will input "tag1,slate1,flag1,check1,5,6" values and expecting output like

tag1,slate1,flag1,check1,5,6,3,4

and if "tag4,slate4,flag4,check4,8,9" record not exists then output will be

tag4,slate4,flag4,check4,8,9,NILL,NILL
0
1
awk -v add='tag1,slate1,flag1,check1,5,6' '
BEGIN{ FS=OFS=","; split(add, arr, ",") }

($1==arr[1] && $2==arr[2] && $3==arr[3] && $4==arr[4]) { append=$5 FS $6 }
END{ print add, (append?append:"NULL,NULL") }' infile

Output:

tag1,slate1,flag1,check1,5,6,3,4

Or doing in another way:

awk -v add='tag4,slate4,flag4,check4,8,9' '
BEGIN{ FS=OFS="," }

{ key=$1 FS $2 FS $3 FS $4; if(index(add, key)==1) append=$5 FS $6 }
END{ print add, (append?append:"NULL,NULL") }' infile

Output:

tag4,slate4,flag4,check4,8,9,NULL,NULL
2
  • is it possible to delete all records with primary key ['tag1,slate1,flag1,check1'] and keep last matching key 'tag1,slate1,flag1,check1,3,4' and after ['tag1,slate1,flag1,check1'] kind records – K Soumya Mar 17 at 6:45
  • @KSoumya change this print add, (append?append:"NULL,NULL") to this print (append?append:"NULL,NULL"), if that's not what you want, then open a new question. – αғsнιη Mar 17 at 6:51
0

awk

add='tag1,slate1,flag1,check1,5,6'
awk -F ',' -v add="$add" '
BEGIN {
  key = add; sub(/(,[^,]+){2}$/, "", key)
  tupl = ",NIL,NIL"
}
{
  do{
    if (index($0, key FS) == 1)
      tupl = FS $(NF-1) FS $NF
  } while (getline > 0)
  $0 = add tupl
};1
' list.csv
tag1,slate1,flag1,check1,5,6,3,4

GNU sed with extended regex mode turned ON -E

# helper variables that make it easy to look
# at n process the pattern space in terms of fields
s=,        S="[^$s]"
F=$s$S+   F2="($F){2}"
add='tag1,slate1,flag1,check4,5,6'
sed -Ee "
  1{H;z;x;s/^/$add/;ba;}

  :loop
    \$tend
    N
    :a
    /^(.*)$F2\n\1$F2\$/h
    s/\n.*//
  bloop

  :end
  G;s/\n\$/,NIL,NIL/;t
  g;s/\n.*($F2\$)/\1/
" list.csv
tag1,slate1,flag1,check4,5,6,NIL,NIL

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.