linux - 在 Bash 脚本中使用带有转义字符的 Awk

标签 linux bash shell awk escaping

我正在为 Linux 系统开发一个 shell 脚本(使用 Bash)。

作为此脚本的一部分,我使用 awk 获取从 ping 请求中丢弃的数据包的百分比。从下面显示的终端执行时,这工作正常:

test=`ping gnu.org -c10 | tail -2`; echo $test | awk '{printf $6 "\b"}'

这会获取丢弃的数据包的百分比,并使用退格转义字符回显它以仅显示“0”而不是棕褐色的“0%”——这是因为该值稍后用作整数值。

在脚本中,代码如下所示:

#Pings the gateway ten times and stores the result
local pingResults=`ping -c10 $gateway | tail -2`

#Uses awk to get the percentage of packets lost using \b to remove the %
local packetsLost=`echo $pingResults | awk '{printf $6 "\b"}'`

我从 packetsLost 返回值并回显它,它给出“0%”,完全忽略\b

有人可以解释为什么在 shell 脚本中会发生这种情况,我该如何补救?

我知道有一些替代方法,例如使用 cut,但我希望这条线尽可能简单高效。

最佳答案

我的天哪!基于字数统计来解析人类可读的字符串是完全不可维护的(“只写”)且不可预测的。尽量避免它。其实很简单:

$ ping -q gnu.org -c10 |\
     gawk '{ if (match ($0, /([[:digit:]]+(\.[[:digit:]]+)?)% packet loss/, a)) print a[1]; }'
0

a[1] 对应于正则表达式中的第一个 () 组。

P. S. 当您解析人类可读的输出时,有必要确保语言环境(即语言)与您在编写脚本时所期望的相同,因此在实际代码中 ping 调用应该如下所示:

local pingResults=$(LANG=C ping -q -c10 "$gateway")

(即使 iputils-ping 似乎没有任何翻译。)

关于linux - 在 Bash 脚本中使用带有转义字符的 Awk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25089568/

相关文章:

C: OpenSSL RSA_private_decrypt() 失败,返回 "error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error”

xml - 验证xml文件+如何将xmllint命令设置为静默模式

bash - 测试是否有任何文件超过 7 天

bash - 在 bash 中,可以将函数调用用作 if 语句中的条件吗?

shell - ZSH历史完成菜单

linux - Linux下应该使用什么库来生成热图?

linux - 如何彻底剥离可执行文件

linux - bash 脚本中的字符串替换给出错误

macos - 如何让 OS X Lion 上的 bash 在选项卡完成期间忽略 .DS_Store 文件?

linux - 如何制作设备/套接字文件的副本