如何选择shell输出的最后一行 [英] how to select the last line of the shell output

查看:1523
本文介绍了如何选择shell输出的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的shell命令.

Hi I have a shell command like this.

s3=$(awk 'BEGIN{ print "S3 bucket path" }
 /Executing command\(queryId/{ sub(/.*queryId=[^[:space:]]+: /,""); q=$0 }
 /s3:\/\//{ print "," $10 }' OFS=',' hive-server2.log)

上面命令的输出是这样的.

The output of the above command like this.

echo $s3

2018-02-21T17:58:22,
2018-02-21T17:58:26,
2018-02-21T18:05:33,
2018-02-21T18:05:34

我只想选择最后一行.我需要这样的最后一个输出.

I want to select the last line only. I need the last output like this.

 2018-02-21T18:05:34

我尝试过这样.

awk -v $s3 '{print $(NF)}' 

不起作用.任何帮助将不胜感激.

Not working.Any help will be appreciated.

推荐答案

通常,command | tail -n 1打印command输出的最后一行.但是,如果command的格式为awk '... { ... print something }',则可以重构为awk '... { ... result = something } END { print result }',以避免产生单独的进程以丢弃其他输出.

In general, command | tail -n 1 prints the last line of the output from command. However, where command is of the form awk '... { ... print something }' you can refactor to awk '... { ... result = something } END { print result }' to avoid spawning a separate process just to discard the other output.

如果您已经在shell变量s3中包含了结果,并且只想打印最后一行,则可以使用参数扩展echo "${s3##*$'\n'}"进行.表示换行符的C样式字符串$'\n'是Bash扩展名,并且用于删除最长匹配前缀的参数扩展运算符##也不是完全可移植的,因此您应确保shebang行说#!/bin/bash ,而不是#!/bin/sh

If you already have the result in a shell variable s3 and want to print just the last line, a parameter expansion echo "${s3##*$'\n'}" does that. The C-style string $'\n' to represent a newline is a Bash extension, and the parameter expansion operator ## to remove the longest matching prefix isn't entirely portable either, so you should make sure the shebang line says #!/bin/bash, not #!/bin/sh

还请注意,没有引号的$s3是一个错误,除非您特别要求外壳程序对该值执行空格标记化和通配符扩展.基本上,除了在某些非常特殊的情况下,您应该始终在变量周围使用双引号.

Notice also that $s3 without quotes is an error unless you specifically require the shell to perform whitespace tokenization and wildcard expansion on the value. You should basically always use double quotes around variables except in a couple of very specific scenarios.

这篇关于如何选择shell输出的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆