Teeteto
Teeteto

Reputation: 25

Save variable from txt using awk

I have a txt in my folder named parameters.txt which contains

PP1 20 30 40 60

PP2 0 0 0 0

I'd like to use awk to read the different parameters depending on the value of the first text field in each line. At the moment, if I run

src_dir='/PP1/'
awk "$src_dir" '{ print $2 }' parameters.txt

I correctly get

20

I would simply like to store that 20 into a variable and to export the variable itself.

Thanks in advance!

Upvotes: 2

Views: 2055

Answers (3)

jaypal singh
jaypal singh

Reputation: 77075

You don't really need awk for that. You can do it in bash.

$ src_dir="PP1"
$ while read -r pattern columns ; do 
      set - $columns
      if [[ $pattern  =~ $src_dir ]]; then 
          variable=$2
      fi
   done < parameters.txt

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246744

shell_pattern=PP1
output_var=$(awk -v patt=$shell_pattern '$0 ~ patt {print $2}' file)

Note that $output_var may contain more than one value if the pattern matches more than one line. If you're only interested in the first value, then have the awk program exit after printing .

Upvotes: 0

fedorqui
fedorqui

Reputation: 289495

If you want to save the output, do var=$(awk expression):

result=$(awk -v value=$src_dir '($1==value) { print $2 }' parameters.txt)

You can make your command more general giving awk the variable with the -v syntax:

$ var="PP1"
$ awk -v v=$var '($1==v) { print $2 }' a
20
$ var="PP2"
$ awk -v v=$var '($1==v) { print $2 }' a
0

Upvotes: 2

Related Questions