Re: bash: var contains full line. How to input this data with spaces into a var

From: Ed Morton (morton_at_lsupcaemnt.com)
Date: 03/30/05


Date: Wed, 30 Mar 2005 13:40:40 -0600


stevenbentley@yahoo.com wrote:
<snip>
> Thanks both for the help.
> I settled on the eval method and this works as i required ...until I
> hit the following:
>
> VAR1='one "two three"; four'
> Now I would like:
> VAR2=one
> VAR3="two three"; #including the " and the ;
> VAR4=four
>
> Using the eval and the awk methods, the " and the ; are both stripped
> off. I have tried using backslash but get syntax problems with eval and
> I'm not even sure how to structure this for awk. Can you help me with
> the quoting here?

Put this:

BEGIN{FS="";nv=1}{
     for (i=1;i<=NF;i++) {
         if ( $i == "\"" ) {
             quoted = !quoted
             $i = "\\" $i
         }
         if ((quoted) || ($i != " ")) {
                 var = var $i
         } else if (($i == " ") && (var != "")) {
                 printf "VAR%s=\"%s\"\n",++nv,var
                 var = ""
         }
     }
}END{ printf "VAR%s=\"%s\"\n",++nv,var }

in a file named "setvars.awk". Then run these commands:

PS1> VAR1='one "two three"; four'
PS1> eval `echo "$VAR1" | gawk -f setvars.awk`
PS1> echo "VAR2=$VAR2\nVAR3=$VAR3\nVAR4=$VAR4"
VAR2=one
VAR3="two three";
VAR4=four

Note that I'm using "gawk" not one of the other awks.

> Thanks
>
> 2nd Question
> I'd like to be able to use the value stored in a variable to determine
> which positional parameter to use. Something like:
> $2=5
> count=2
> echo $($2) #5 should be outputted

eval echo \$$2

> Obviously the above does not work. How can I achieve this?
>
> Many Thanks for all help!
>

Regards,
        
        Ed.



Relevant Pages

  • Re: Can someone help me out of this?
    ... William James wrote: ... If the above are NOT true, then why do we do awk at all? ... condition plus a non-NR condition, no matter what that non-NR condition ...
    (comp.unix.shell)
  • Re: Can someone help me out of this?
    ... If the above are NOT true, then why do we do awk at all? ... that the order of evaluation matters. ... In this case it's the null string. ...
    (comp.unix.shell)
  • Re: Can someone help me out of this?
    ... If the above are NOT true, then why do we do awk at all? ... condition plus a non-NR condition, no matter what that non-NR condition ...
    (comp.unix.shell)
  • Re: getline
    ... I dunno - AWK (more specifically TAWK) doesn't let me do the equivalent of ... if you are doing a line-by-line compare between two ... Something I once did in AWK as a way of comparing two very large, ...
    (comp.lang.awk)