[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: scripting question: to parse data with varname=value pattern the easiest way?

>> On Mon, 01 Nov 2010 15:49:01 +0800, 
>> Zhang Weiwu <zhangweiwu@realss.com> said:

Z> A program output is like this:
Z>   result_01: a="23" b="288" c="A_string" ac="34"
Z>   result_02: a="23" b="28" c="A_string_too" dc="3"
Z>   ....

Z> I am writing a script to output values of b if b is in the result set.

   If your data is trustworthy and follows shell assignment rules like the
   example above, you can abuse sh/ksh/bash:


     sample='result_01: a="23" b="288" c="A_string" ac="34"
     result_02: a="23" c="A_string_too" dc="3"
     result_03: a="23" b="28" c="A_string_too" dc="3"'

     echo "$sample" | while read str
         unset b       # or whatever you're looking for
         set $str      # will fail horribly if $str is empty
         eval "$@"
         test "$b" && echo "$result $b"
     exit 0

   On the other hand, if someone sneaks something like
       result_04: dc="3" rm /something/valuable

   into your program output, you'll get a nasty surprise.

Karl Vogel                      I don't speak for the USAF or my company

Most users (myself included) spend most of their time in front of a computer
in a kind of fuzzy autopilot mode, and anything that creates ripples on that
placid lake of unawareness is going to be noticed as a disproportionately
significant problem.                 --David Harris, creator of Pegasus Mail

Reply to: