0

The file I'm searching (fruit.text) looks something like the below snippet, the data appears in random order that I cannot control.

....fruit=apple,...qty=3,...condition=bad,....

...qty=4,...condition=great,...fruit=orange,...

...condition=ok,...qty=2,...fruit=banana,...

My Grep command is: grep -Eo 'fruit.[^,]*'\|'qty.[^,]*'\|'condition.[^,]*' fruit.txt

This results in output like:

fruit=apple

qty=3

condition=bad

qty=4

condition=great

fruit=orange

condition=ok

qty=2

fruit=banana

Which is correct, however, I'm looking for the output to be ordered as I specified in the grep cmd. ie, exactly like the below:

fruit=apple

qty=3

condition=bad

fruit=orange

qty=4

condition=great

fruit=banana

qty=2

condition=ok

0

2 Answers 2

1

A solution with gawk:

first i added some extra ',' to the input:

....,fruit=apple,...,qty=3,...,condition=bad,....
...,qty=4,...,condition=great,...,fruit=orange,...
...,condition=ok,...,qty=2,...,fruit=banana,...

Then i wrote this awk script (fruit.awk):

{ fruit ="";
  qty="";
  condition="";
  for (i = 1;i <= NF; i++){
        delete a;
        split($i,a,"=");
        if (a[1]=="fruit" ) { fruit=a[2]; }
        if (a[1]=="qty") { qty=a[2] }
        if (a[1]=="condition") { condition=a[2] }
   }
}
{ print "fruit=" fruit;
  print "qty=" qty;
  print "condition=" condition;
}

output of: gawk -F , -f fruit.awk fruit.txt:

fruit=apple
qty=3
condition=bad
fruit=orange
qty=4
condition=great
fruit=banana
qty=2
condition=ok
Sign up to request clarification or add additional context in comments.

Comments

0

Using sed in some steps:

sed -E 's/^/,/;
        s/(.*),(condition[^,]*)/\2\r,\1/;
        s/(.*),(qty=[^,]*)/\2,\1/;
        s/(.*),(fruit=[^,]*)/\2,\1/;
        s/\r.*//;
        s/,/\n/g' input.txt

I start with inserting a , for input where the interesting data starts in the first field.
After condition I add a \r, so I can remove the garbage after finding the fruit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.