bash将输出存储为变量

con*_*ied 5 linux bash

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

将返回从大文本文件中提取的列表中的最大值,但如何将输出存储为变量?

Lee*_*ton 8

使用命令替换:

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

另外,为了便携性,我建议总是使用-n1参数head.我遇到了几个使用-1不起作用的化身.