Awk in ksh shell script - help

Hello,
Im a beginner. Im writing a ksh script with awk. Is it possible to assign the output of the awk to a shell variable?

Like,
shell_variable= awk '$1 == "shell" {abc= $2 }' /tmp/cust_det
echo $shell_variable

Please excuse my ignorance. Thanks in advance.

use backquote(`)

shell_variable= `awk '$1 == "shell" {abc= $2 }' /tmp/cust_det`
echo $shell_variable

Thank you for the correction :slight_smile:

How do i compare the shell argument say $1 with awk's $1 ?
or a shell variable with awk's $1 ??

shell_variable= `awk '$1 == "$shell" {abc= $2 }' test_file`
echo $shell_variable

I got something like this , it seems to work...

shell_variable= `awk '$1 == shell {print $2 } shell="$1" ' test`
echo $shell_variable

Any other better way???

If the goal is to display the output from the backticks, then the backticks and the echo are of course needless. But to actually capture the output from the awk script into a variable, that's how you do it. Now let's turn to how to mix shell and awk variables.

You can mix shell and awk by playing around with quotes. Most often, you need quoting in order to pass the awk script to awk as a single string (unless of course your script is so simple that it's a single token, from the shell's point of view) and conventionally, we use single quotes to prevent the shell from messing with the string's contents. But if you do want the shell to, say, place the value of its first argument inside the string, then you can do that by relaxing the quoting.

awk '$1 == "'"$1"'" { print $2 }' test

The tricky quoting there is a closing single quote, followed by $1 in double quotes, followed by an opening single quote. Inside the awk script, all of this is in another set of double quotes, to mark it as a string in awk. The "seesaw quoting" causes the shell to interpolate the value of $1 smack dab into the middle of the awk script. So if the value of the shell's variable $1 is "shell", then the awk interpreter will end up executing the following script:

$1 == "shell" { print $2 }

So the awk script is pieced together from three parts: $1 == " (in single quotes) followed by the value of the shell variable $1 (in double quotes), followed by " { print $2} (in single quotes).

Some newer awk interpreters allow you to avoid this tricky quoting by using the -v switch, but the original, ancient awk didn't have that.

awk -v var="$1" '$1 == var { print $2 }' test

Here, the awk variable var is assigned on the command line to the value of the shell variable $1.