使用 bash shell 脚本和 awk 提取子字符串
因此,我有一个名为“dummy”的文件,其中包含以下字符串:
"There is 100% packet loss at node 1".
我还有一个小脚本,我想用它来从此文件中获取百分比。脚本如下。
result=`grep 'packet loss' dummy` |
awk '{ first=match($0,"[0-9]+%")
last=match($0," packet loss")
s=substr($0,first,last-first)
print s}'
echo $result
在这种情况下,我希望 $result 的值基本上为 100%。但由于某种原因,它只打印出一个空白字符串。谁能帮助我吗?
So, I have a file called 'dummy' which contains the string:
"There is 100% packet loss at node 1".
I also have a small script that I want to use to grab the percentage from this file. The script is below.
result=`grep 'packet loss' dummy` |
awk '{ first=match($0,"[0-9]+%")
last=match($0," packet loss")
s=substr($0,first,last-first)
print s}'
echo $result
I want the value of $result to basically be 100% in this case. But for some reason, it just prints out a blank string. Can anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要在
awk
命令末尾添加结束反引号,但最好使用$()
代替:但您可以这样做:
You would need to put the closing backtick after the end of the
awk
command, but it's preferable to use$()
instead:but you could just do:
尝试
一下。
Try
instead.
当您不知道百分比数字在哪里时,可以使用下面的解决方案(并且不需要将 awk 与 grep 一起使用)
the solution below can be used when you don't know where the percentage numbers are( and there's no need to use awk with greps)
您可以使用
expr
单独使用 bash 来完成此操作。这会提取与
\( \)
中的正则表达式匹配的子字符串。You could do this with bash alone using
expr
.This extracts the substring matching the regex within
\( \)
.在这里,我假设您感兴趣的输出行严格遵守您的示例,百分比值是唯一的变化。
有了这个假设,您实际上不需要比以下更复杂的东西:
这实际上意味着“打印其中包含‘数据包丢失’的任何行的第三个字段”。默认情况下,awk 将空格视为字段分隔符,这非常适合您。
如果您要做的不仅仅是打印百分比,您可以使用反引号将结果保存到 shell 变量,或将输出重定向到文件。但您的示例代码只是将百分比回显到标准输出,然后退出。单行线做同样的事情。不需要反引号或 $() 或任何其他 shell 机制。
注意:根据我的经验,将 grep 的输出通过管道传输到 awk 通常会做 awk 本身可以完成的事情。
Here I'm assuming that the output lines you're interested in adhere strictly to your example, with the percentage value being the only variation.
With that assumption, you really don't need anything more complicated than:
This quite literally means "print the 3rd field of any lines containing 'packet loss' in them". By default awk treats whitespace as field delimiters, which is perfect for you.
If you are doing more than simply printing the percentage, you could save the results to a shell variable using backticks, or redirect the output to a file. But your sample code simply echoes the percentages to stdout, and then exits. The one-liner does the exact same thing. No need for backticks or $() or any other shell machinations whatsoever.
NB: In my experience, piping the output of grep to awk is usually doing something that awk can do all by itself.