【发布时间】:2014-08-01 22:24:30
【问题描述】:
我正在为 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"}'`
我从 packetLost 中返回值并回显它,它给出“0%”,完全忽略了 \b
有人能解释一下为什么在 shell 脚本中会发生这种情况以及我该如何解决这个问题吗?
我了解有其他替代方法,例如使用 cut,但我希望尽可能保持线路简单高效。
【问题讨论】:
-
终端的shell和脚本的一样吗?
-
是的,两者都使用 bash
-
为什么不在 awk 中直接关闭
gsub%字符,而不是玩打印转义技巧? -
试试
printf("%s", substr($6, 1, length($6)-1))。 -
我觉得 Awk 是实现我所需要的最干净、最简单的方法。
标签: linux bash shell awk escaping