Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign AWK result to variable [duplicate]

This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';") 

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

echo $INDEXCOUNT | awk '{print $3}' 

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

RETURNCOUNT=$INDEXCOUNT | awk '{print $3}' 
like image 612
user739866 Avatar asked May 17 '11 13:05

user739866


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

How do I save an awk output?

The third statement, i.e., close(cmd, "to"), closes the to process after competing its execution. The next statement cmd |& getline out stores the output into out variable with the aid of getline function. The next print statement prints the output and finally the close function closes the command.

How do I specify a delimiter in awk?

The AWK Field Separator (FS) is used to specify and control how AWK splits a record into various fields. Also, it can accept a single character of a regular expression. Once you specify a regular expression as the value for the FS, AWK scans the input values for the sequence of characters set in the regular expression.


2 Answers

The following works correctly on bash:

 a=$(echo '111 222 33' | awk '{print $3;}' )  echo $a # result is "33" 

Another option would be to convert the string to an array:

 a="111 222 333"  b=($a)   echo ${b[2]}  # returns 333 
like image 76
nimrodm Avatar answered Sep 22 '22 19:09

nimrodm


You can try this:

RETURNCOUNT=`echo $INDEXCOUNT | awk '{print $3}'` 

The idea is to include any shell command between backticks to get the result into a variable.

like image 27
Mayank Avatar answered Sep 22 '22 19:09

Mayank