【问题标题】:bash store output as a variablebash 将输出存储为变量
【发布时间】:2012-10-03 08:39:00
【问题描述】:
grep -A 26 "some text" somefile.txt |
   awk '/other text/ { gsub(/M/, " "); print $4 }' |
   sort -n -r | uniq | head -1

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

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    使用command substitution:

    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 不起作用的版本。

    【讨论】:

      【解决方案2】:

      对于未嵌套的情况,后引号也可以:

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

      【讨论】:

        【解决方案3】:

        我建议

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-03
          • 2021-07-04
          • 2017-02-20
          • 2019-11-05
          • 2020-09-19
          • 2020-07-04
          相关资源
          最近更新 更多