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.

6
  • Explain why each resulting record should end with TXN Commented Feb 6, 2020 at 8:01
  • TXN shown Trasaction status with the code success or failure... 200 shows success 209 failure.... Commented Feb 6, 2020 at 8:03
  • even I can get the values that would also help...30,209 70,200 90,200 Commented Feb 6, 2020 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)? Commented Feb 6, 2020 at 8:10
  • no there is only one value between Amount. It was a xml file which I have changed to csv value.. Commented Feb 6, 2020 at 8:13

1 Answer 1

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.

1
  • Thanks Kusalananda!!!! You made my day...Cheers Commented Feb 6, 2020 at 8:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.