2

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!

1

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for the quick answer! I've tried the former command, but I get Cannot open `{ print $2 }'
Ok! See my updated answer, I did not check your expression. Now I've done it.
Getting closer but still not there yet :) I get no errors, but an echo $result gives a blank outcome!
Then let's work a little bit more on it! Do you previously set the variable with src_dir="PP1"? Otherwise, does this work to you? --> result=$(awk -v value="PP1" '($1==value) { print $2 }' parameters.txt)?
Exactly, I needed to take the slash out. I've used a workaround though, and now it works. Thanks!
|
2

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

1 Comment

You can leave feedback in the comments instead of updating the answer.
0
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 .

1 Comment

What would be the output variable?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.