You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何选取Shell命令输出的最后一行?求可行解决方案

Grab the Last Line of Shell Command Output

Hey there! Let me share a few straightforward, reliable methods to extract just the last line from your shell command's output—these should work across most Unix-like shells (bash, zsh, etc.):

  • Use tail (the simplest approach)
    This is the go-to tool for this exact task. Pipe your command's output to tail -n 1, where -n 1 specifies you only want the final line:

    your_shell_command | tail -n 1
    

    If your command also outputs to stderr (error messages) and you want to include those in the output to grab the last line, redirect stderr to stdout first:

    your_shell_command 2>&1 | tail -n 1
    
  • Use sed for line-specific filtering
    sed lets you target the last line with the $ symbol (which represents the final line in the input). The -n flag tells sed not to print lines by default, and p prints the matched line:

    your_shell_command | sed -n '$p'
    
  • Use awk with an END block
    awk executes the END block only after processing all input lines. Inside this block, we print the last line that was processed:

    your_shell_command | awk 'END{print}'
    

All these methods should handle most standard output scenarios. If you're still hitting issues, it might be due to unusual output formatting (like hidden control characters or empty trailing lines), but these core tools are almost always the solution.

内容的提问来源于stack exchange,提问作者Teju Priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:02:31