簡體   English   中英

bash將輸出存儲為變量

[英]bash store output as a variable

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

將返回從大文本文件中提取的列表中的最大值,但如何將輸出存儲為變量?

使用命令替換

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

另外,為了便攜性,我建議總是使用-n1作為head的參數。 我遇到過幾個版本,其中使用-1不起作用。

對於unnested案例,返回引號也會起作用:

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

我建議

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM