0

Need your expert advice on this

AMOUNT,30,/AMOUNT,MESS,Am,/MESS,AMOUNT,30,/AMOUNT,TXN,209,/TXN  
MESS,SU,/MESS,TXN,200,/TXN,AMOUNT,70,/AMOUNT       
TXN,200,/TXN,AMOUNT,90,/AMOUNT,MESS,SUM,/MESS,AMOUNT,90,/AMOUNT   

There is no particular order in which AMOUNT or TXN gets generated but each line has these two value. Also there is a duplicate AMOUNT entry on some rows.

I need an output as below

AMOUNT,30,/AMOUNT,TXN,209,/TXN   
AMOUNT,70,/AMOUNT,TXN,200,/TXN   
AMOUNT,90,/AMOUNT,TXN,200,/TXN    

It will be very helpful if anyone can help me on this.

  • Explain why each resulting record should end with TXN – RomanPerekhrest Feb 6 at 8:01
  • TXN shown Trasaction status with the code success or failure... 200 shows success 209 failure.... – Amit10504 Feb 6 at 8:03
  • even I can get the values that would also help...30,209 70,200 90,200 – Amit10504 Feb 6 at 8:04
  • Are AMOUNT and /AMOUNT kinda working as a opening and closing "tag" for the value? Can there be multiple values between AMOUNT and /AMOUNT (or between TXN and /TXN)? – Kusalananda Feb 6 at 8:10
  • no there is only one value between Amount. It was a xml file which I have changed to csv value.. – Amit10504 Feb 6 at 8:13
1
awk -F ',' '
BEGIN { OFS = FS }
{
    a = t = "N/A"

    for (i = 1; i < NF; ++i)
        if ($i == "AMOUNT")
            a = $(i + 1)
        else if ($i == "TXN")
            t =$(i + 1)

    $0 = ""

    $1 = "AMOUNT"
    $2 = a
    $3 = "/AMOUNT"

    $4 = "TXN"
    $5 = t
    $6 = "/TXN"

    print
}' file

This looks for the strings AMOUNT and TXN within the comma-delimited fields of each line. When AMOUNT is found, a is assigned the data of the next field. In a similar way, t is assigned the TXN value. If either of the values can't be found, it will be the string N/A.

The output is then generated.

A shorter version:

awk -F ',' '
{
    a = t = "N/A"

    for (i = 1; i < NF; ++i)
        if ($i == "AMOUNT")
            a = $(i + 1)
        else if ($i == "TXN")
            t =$(i + 1)

    printf "AMOUNT,%s,/AMOUNT,TXN,%s,/TXN\n", a, t
}' file

Only the outputting bit is different. Instead of outputting a record, we output a string produced by printf.

|improve this answer|||||
  • Thanks Kusalananda!!!! You made my day...Cheers – Amit10504 Feb 6 at 8:59

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.