justaguy
justaguy

Reputation: 3022

awk to reorder lines in output file

In the below awk I am printing out specific tags in the input. However, I can not seem to get line 2 in the current output to be line 1. It looks like because of the way the input is formatted that is why the output is ordered in the way it is. I can not seem to change it in the awk. Thank you :).

input

"barcodedSamples": {"MEV37": {"barcodeSampleInfo": {"IonXpress_007": {"controlSequenceType": "", "expName": "R_2016_09_20_12_47_36_user_S5-00580-7-Medexome",

awk

awk -F"[]\":{}, ]*" '
    {for (i=1; i<NF; i++)   {if ($i =="expName") print $(i+1)
                             if ($i =="barcodeSampleInfo") print $(i+1) " " $(i-1)
                            }
    }
' input

current output

IonXpress_007 MEV37
R_2016_09_20_12_47_36_user_S5-00580-7-Medexome

desired output

R_2016_09_20_12_47_36_user_S5-00580-7-Medexome
IonXpress_007 MEV37

Upvotes: 1

Views: 231

Answers (3)

Claes Wikner
Claes Wikner

Reputation: 1517

awk -F\" '{print $(NF - 1)"\n" $8,$4}'  file

R_2016_09_20_12_47_36_user_S5-00580-7-Medexome
IonXpress_007 MEV37

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185053

With :

INPUT FILE

{
   "barcodedSamples" : {
      "MEV37" : {
         "barcodeSampleInfo" : {
            "IonXpress_007" : {
               "controlSequenceType" : "",
               "expName" : "R_2016_09_20_12_47_36_user_S5-00580-7-Medexome"
            }
         }
      }
   }
}

COMMAND

% jq '.barcodedSamples.MEV37.barcodeSampleInfo.IonXpress_007.expName' file.json

OUTPUT

"R_2016_09_20_12_47_36_user_S5-00580-7-Medexome"

Or with :

% node                                                                                                         
> j = { "barcodedSamples": {"MEV37": {"barcodeSampleInfo": {"IonXpress_007": {"controlSequenceType": "", "expName": "R_2016_09_20_12_47_36_user_S5-00580-7-Medexome"}}}}}
{ barcodedSamples: { MEV37: { barcodeSampleInfo: [Object] } } }
> console.log(j.barcodedSamples.MEV37.barcodeSampleInfo.IonXpress_007.expName)
R_2016_09_20_12_47_36_user_S5-00580-7-Medexome

NOTE

now that you understand how to access any part, just modify this a bit to fully fits your needs

Upvotes: 1

RotatingPieces
RotatingPieces

Reputation: 413

You can create one or more arrays in the BEGIN function. When processing lines do not print. Instead of printing do append to these arrays in the order you want. In the END function print out these arrays.

Upvotes: 1

Related Questions