Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash store output as a variable

Tags:

linux

bash

grep -A 26 "some text" somefile.txt |
   awk '/other text/ { gsub(/M/, " "); print $4 }' |
   sort -n -r | uniq | head -1

will return the largest in a list pulled from a large text file, but how do I store the output as a variable?

like image 969
confusified Avatar asked Oct 03 '12 08:10

confusified


People also ask

How do you assign a output to a variable in Linux?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'


2 Answers

Use command substitution:

my_var=$(grep -A 26 "some text" somefile.txt |
   awk '/other text/ { gsub(/M/, " "); print $4 }' |
   sort -n -r | uniq | head -n1)

Also, for portability, I would suggest always using -n1 for the argument of head. I've come across a couple of incarnations of it where using -1 doesn't work.

like image 129
Lee Netherton Avatar answered Oct 13 '22 07:10

Lee Netherton


For unnested cases back quotes will work too:

variable=`grep -A 26 "some text" somefile.txt |   
awk '/other text/ { gsub(/M/, " "); print $4 }' |  
sort -nru | head -1`
like image 40
Aki Suihkonen Avatar answered Oct 13 '22 07:10

Aki Suihkonen