Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving awk output to variable [duplicate]

Can anyone help me out with this problem?

I'm trying to save the awk output into a variable.

variable = `ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}'` printf "$variable" 

EDIT: $12 corresponds to a parameter running on that process.

Thanks!

like image 812
Jeremy Avatar asked Sep 06 '13 01:09

Jeremy


People also ask

How do you store output of awk in a variable?

`awk` command uses '-v' option to define the variable. In this example, the myvar variable is defined in the `awk` command to store the value, “AWK variable” that is printed later. Run the following command from the terminal to check the output.

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.

What is awk '{ print $4 }'?

The AWK language is useful for manipulation of data files, text retrieval and processing. -F <value> - tells awk what field separator to use. In your case, -F: means that the separator is : (colon). '{print $4}' means print the fourth field (the fields being separated by : ).

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.


1 Answers

#!/bin/bash  variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'` echo $variable 

Notice that there's no space after the equal sign.

You can also use $() which allows nesting and is readable.

like image 116
vvens Avatar answered Sep 28 '22 05:09

vvens