Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable in current shell from awk

Tags:

Is there a way to set a variable in my current shell from within awk?

I'd like to do some processing on a file and print out some data; since I'll read the whole file through, I'd like to save the number of lines -- in this case, FNR.

Happens though I can't seem to find a way to set a shell variable with FNR value; if not this, I'd have to read the FNR from my output file, to set, say num_lines, with FNR value.

I've tried some combinations using awk 'END{system(...)}', but could not manage it to work. Any way around this?

like image 816
Rubens Avatar asked Jan 24 '13 15:01

Rubens


People also ask

How do you pass variables from awk to shell?

Passing variables from 'awk' to the shell (its parent process) can be done by 'eval'ing the 'awk' (or an entire pipleline ending with an 'awk' if desired), and having the 'awk' print text which will cause its parent shell to put the information you want into variables.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

How do you pass external variables to awk?

In the preceding method, variables are specified as key-value pairs, separated by a space, and (v1=$var1 v2=$var2 ) as command arguments to awk soon after the BEGIN , { } , and END ...


1 Answers

Here's another way.

This is especially useful when when you've got the values of your variables in a single variable and you want split them up. For example, you have a list of values from a single row in a database that you want to create variables out of.

val="hello|beautiful|world" # assume this string comes from a database query read a b c <<< $( echo ${val} | awk -F"|" '{print $1" "$2" "$3}' )  echo $a #hello echo $b #beautiful echo $c #world 

We need the 'here string' i.e <<< in this case, because the read command does not read from a pipe and instead reads from stdin

like image 141
Abbas Gadhia Avatar answered Oct 28 '22 07:10

Abbas Gadhia