LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   pass value from awk back to bash shell (https://www.linuxquestions.org/questions/programming-9/pass-value-from-awk-back-to-bash-shell-297495/)

cjs_pro 03-04-2005 03:27 AM

pass value from awk back to bash shell
 
Hi all,

Here is my bash script:

VERSION=""
awk 'BEGIN {
file='"'$SOURCE_PATH'"'
while ( (getline aline < file) > 0 )
{
if ($aline ~ /Id=[0-9]*.[0-9]*/)
{
print aline
VERSION=aline
break
}
}
}'
echo "$VERSION"

What I tried to do is to use awk get a line matching a pattern and pass the line back to bash shell script. I got "print aline" outputing the matched line. However, I was unable to get VERSION out of awk. So, echo "$VERSION" has empty. Could anyone tell me how to get a value back to bash shell from awk?

Thank you

Hko 03-04-2005 05:24 AM

You can not set a bash variable directly from awk. But you can have bash execute awk and assign its output to a variable with $(command).

Like this:
Code:

#!/bin/bash

SOURCE_PATH=file.txt

VERSION=$(awk 'BEGIN {
    file="'$SOURCE_PATH'"
    while ( (getline aline < file) > 0 ) {
      if (aline ~ /Id=[0-9]*.[0-9]*/) {
        print aline
        break
      }
    }
  }')

echo "Version line: $VERSION"

But in your case (just print 1 matching line) I'd use grep instead of awk:
Code:

#!/bin/bash

SOURCE_PATH=file.txt
VERSION=$(grep 'Id=[0-9]*.[0-9]*' "$SOURCE_PATH")
echo "Version line: $VERSION"

Or at least simplify the awk script:
Code:

#!/bin/bash

SOURCE_PATH=file.txt
VERSION=$(awk '/Id=[0-9]*.[0-9]*/ {print $0}'  "$SOURCE_PATH")
echo "Version line : $VERSION"


cjs_pro 03-07-2005 04:53 PM

Hi HKO,

Thank you. The short form of awk is working perfectly with a minor change on wildcard (* -> +) to make an exact match in my case.

Thank you once more
Chris


All times are GMT -5. The time now is 11:29 PM.