如何选取Shell命令输出的最后一行?求可行解决方案
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 totail -n 1, where-n 1specifies you only want the final line:your_shell_command | tail -n 1If 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 1Use
sedfor line-specific filteringsedlets you target the last line with the$symbol (which represents the final line in the input). The-nflag tellssednot to print lines by default, andpprints the matched line:your_shell_command | sed -n '$p'Use
awkwith an END blockawkexecutes theENDblock 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

