简体   繁体   English

重击一线返回子字符串

[英]Bash one-liner to return substring

My string is: 我的字符串是:

 PING google.com (216.58.217.206) 56(84) bytes of data. --- google.com ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2002ms rtt min/avg/max/mdev = 4.258/4.532/4.907/0.274 ms

I want to return the 0 in the 0%. 我想在0%中返回0。

The problem is this string is of variable length, but there is only one percent character. 问题在于此字符串的长度可变,但是只有百分之一的字符。 I am trying to retrieve the integer (or decimal) value of the packet loss when I have this string in a bash variable. 当我在bash变量中包含此字符串时,我尝试检索数据包丢失的整数(或十进制)值。

I have tried with cut and awk, but I am racking my brain on this one. 我已经尝试过用cut和awk进行操作,但是我正在为此绞尽脑汁。

Thanks! 谢谢!

Changing the value for demonstration purposes: use a regular expression and capture the digits before the percent sign 出于演示目的更改值:使用正则表达式并捕获百分号前的数字

$ str=' PING google.com ... 3 packets transmitted, 3 received, 42% packet ...'

$ [[ $str =~ ([0-9]+)% ]] && num=${BASH_REMATCH[1]}

$ echo $num
42

using GNU grep using perl-compatible regex: 使用与perl兼容的正则表达式使用GNU grep:

$ grep -oP '\d+(?=%)' <<<"$str"
42

sed

sed -r 's/.*\b([0-9]+)%.*/\1/' <<< $str

如果您的数据与所示示例相同,那么以下内容可能会对您有所帮助。

awk '{print $18+0}' Input_file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM