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

将返回从大型文本文件中拉出的列表中的最大值,但是如何将输出存储为变量?bash存储输出作为变量

回答

7

使用command substitution

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

此外,对于便携性,我总是会用-n1head参数建议。我遇到了几个使用-1不起作用的化身。

0

我建议

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

对于嵌套的情况下,反引号将工作太:

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