【问题标题】:Bash how to edit a variableBash如何编辑变量
【发布时间】:2022-07-11 23:08:04
【问题描述】:

我是使用 bash 的新手。现在我要读取一个值,但是控制台的输出太长了,我只想把它缩短到具体的值。

netstat -m

24270/3315/27585 mbufs in use (current/cache/total)
4142/1724/5866/1000000 mbuf clusters in use (current/cache/total/max)
40/1478 mbuf+clusters out of packet secondary zone in use (current/cache)
0/145/145/524288 4k (page size) jumbo clusters in use (current/cache/total/max)
0/0/0/524288 9k jumbo clusters in use (current/cache/total/max)
0/0/0/83968 16k jumbo clusters in use (current/cache/total/max)
...

现在我想在第二行找到 5866 并将其包装在一个变量中。 目前我的脚本如下所示:

mbuf_stat=$(netstat -m)
mbuf=$mbuf_stat
mbuf=${mbuf#*)}
mbuf=${mbuf#*/}
mbuf=${mbuf#*/}
mbuf=${mbuf%%/*}
echo "$mbuf"

有没有更简单的方法来做到这一点?这对我来说似乎很复杂。不幸的是,我还没有找到更简单的方法。

【问题讨论】:

    标签: bash


    【解决方案1】:

    为此使用awk

    mbuf=$(netstat -m | awk -F'/' 'NR == 2 { print $3; exit }')
    

    -F'/' 使 / 成为字段分隔符。 NR == 2 匹配文件的第二行。 print $3 打印第三个字段,其中包含5866,然后exit 退出脚本。

    【讨论】:

      【解决方案2】:

      这个呢:

      mbuf=$(netstat -m | grep "mbuf clusters in use" | awk -F/ '{print $3}')
      

      Barmar 的答案不同的是,我正在寻找包含“正在使用的mbuf 集群”的行,而不是假设它是第二个。

      【讨论】:

        猜你喜欢
        • 2020-01-19
        • 1970-01-01
        • 2021-03-23
        • 2013-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 2017-05-13
        相关资源
        最近更新 更多