简体   繁体   中英

How do I set a built in variable in awk command to global variable?

Currently, my script parses through a file and looks for specific patterns. Each pattern is different from the other and are mutually exclusive within the file. eg If '$identifier1' is found, then '$identifier2' and '$identifier3' cannot be in the file.

exist=`awk -v v1="$identifer1" -v v2="$identifier2" -v v3="$identifier3" 'BEGIN{FS=":"; OFS="-"} $2 == v1 || $2 == v2 || $2 == v3 {print}' $file`

Here is the issue: during the comparison ($2 == v1 || $2 == v2 || $2 == v3), how can I set $2 as a global variable where I can use it outside of the awk command?

Any help is appreciated.

Could you please try following once but your question is not clear. In case you want to check a different field than 2nd then change value of variable named field_value and awk will look for that specific field then.

field_value="2"
exist=$(awk -v v1="$identifer1" -v v2="$identifier2" -v v3="$identifier3" -v field="$field_value" 'BEGIN{FS=":"; OFS="-"} $field == v1 || $field == v2 || $field == v3 {print}' "$file")

Maybe can't directly, but if a temporary IO is ok with you...
You can write $2 to a temporary file and later read into variable, like this:

exist=`awk -v v1="$identifer1" -v v2="$identifier2" -v v3="$identifier3" 'BEGIN{FS=":"; OFS="-"} $2 == v1 || $2 == v2 || $2 == v3 {print} {printf $2>"_tmpfile_for_v_"}' $file`
tmpv=$(<_tmpfile_for_v_)
rm _tmpfile_for_v_

Now you can use the $tmpv stored $2 .

Btw the awk command can improve a little bit:

awk -v v1="$identifer1" -v v2="$identifier2" -v v3="$identifier3" 'BEGIN{FS=":"; OFS="-"} {printf $2>"_tmpfile_for_v_"} $2 == v1 || $2 == v2 || $2 == v3 ' $file

Where no block given, {print} is implied.

You did not give testdata, so I will demonstrate how you can set an extra variable with a simplified question.
Suppose you have a file with only one line starting with 1 (a line like 1 2 3 ).
How can you use awk for filling two variables, one with the line starting with 1 and one with the second field?
You can find the line with

   line=$(awk '/^1/ {print}' file)

Now you would like to do something like

  awk '/1^/ {print "line=" $0; print "field2=" $2}' file

When you know that the line doesn't has a # , you can use

IFS='#" read -r line field2 <<< $(awk '/^1/ {print $0 "#" $2}' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM