Passing awk variables to shell

Hi.
I need to parse file and assign some values to variables, right now i do like below

MYHOMEDIR=`awk '/Home/ {print $NF}' output.txt`
MYSHELL=`awk '/Shell/ {print $NF}' output.txt`
PRGRP=`awk '/Primary/ {print $NF}' output.txt`
SECGRP=`awk '/Second/ {print $NF}' output.txt`

In this case, AFAIK, output.txt is being opened 4 times. This is not good, because output.txt could be quite large. I beleive this can be done in one query. Pls assist.

Save below code as 'var.sh' and chmod 755 var.sh

#! /bin/sh
awk '
  /Home/    { v="MYHOMEDIR";printf("%s=%s;export %s\n",v,$NF,v) }
  /Shell/   { v="MYSHELL";printf("%s=%s;export %s\n",v,$NF,v) }
  /Primary/ { v="PRGRP";printf("%s=%s;export %s\n",v,$NF,v) }
  /Second/  { v="SECGP";printf("%s=%s;export %s\n",v,$NF,v) }
' output.txt

You need to get the shell to do two parses before execution using 'eval'

eval `./var.sh`

I have assigned first column as the variable name ..

$ awk '/(Home|Shell|Primary|Second)/ {print $1"="$NF}' infile > infile1

$ chmod 755 infile1

$ . ./infile1
 
$ echo $Home $Shell $Primary $Second
2 3 4 6
1 Like

Another way ....

set $(awk '/Home/ { home=$NF }
     /Shell/ { shell=$NF }
     /Primary/ { primary=$NF }
     /Second/ { second=$NF }
     END { print home, shell, primary, second }' infile)

MYHOMEDIR=$1; MYSHELL=$2; PRGRP=$3; SECGRP=$4;

echo $MYHOMEDIR
echo $MYSHELL
echo $PRGRP
echo $SECGRP

Cool, but it is not working if i use ":" as filed separator and values with spaces. How to resolve this?

Provide some input file contents and expected output ..

Input file:

    Account Owner     : me
        Description       : me myself
        Login               : mylogin
        ID                   : 43303993
        Application       : test
        UID Number        : 3017256
        Password          : (encrypted)ololo
        Primary Group     : (451) testunix
        Secondary Group   : dialer wheel webgroup
        Home Directory    : /home/me
        Login Shell       : /usr/bin/ksh

I want to assign to variables value of fields "Primary Group" "Secondary Group" "Home Directory" "Login Shell". "Secondary Group" value could contain spaces

Please try to post the actual sample to save time.
You must remove the spaces in LHS to make available in UNIX.

eval $(awk -F: '/(Primary Group|Secondary Group|Home Directory|Login Shell)/ {gsub(/[ ][ ]*/,"",$1);print $1"=\""$2"\""}' file)
$ echo $PrimaryGroup
(451) testunix
$ echo $SecondaryGroup
dialer wheel webgroup
$ echo $HomeDirectory
/home/me
$ echo $LoginShell
/usr/bin/ksh
$

It is not working for me

testhost$ eval $(awk -F: '/(Primary Group|Secondary Group|Home Directory|Login Shell)/ {gsub(/[ ][ ]*/,"",$1);print $1"=\""$2"\""}' output)
awk: syntax error near line 1
awk: illegal statement near line 1
testhost$ uname -a
SunOS testhost 5.8 Generic_117350-46 sun4u sparc SUNW,Sun-Fire-V240

use nawk

1 Like

Many thanks