sed / grep 随机无法修剪字符串

sed / grep 随机无法修剪字符串

我正在使用 bash 脚本,该脚本将从文本文件加载内容并相应地提取数据。问题是有时提取的数据前面有一个点。

代码:

function str_extract() {
 pattern=$1
 # Extract
 res=`grep "$pattern" $log | sed "s/$pattern//g"`
 # Drop trailing ...
 res=`echo $res | sed 's/[.][.][.]//g'`
 # Trim
 res=`echo $res | sed 's/^ *//g' | sed 's/ *$//g'`
 echo  $res
}

  download=`str_extract "Download: "`
  upload=`str_extract "Upload: "`

数据:

Retrieving speedtest.net configuration...
Testing from Telecomunicazioni S.p.A. ...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Coolnetwork (Arezzo) [26.09 km]: 111.547 ms
Testing download speed................................................................................
Download: 2.06 Mbit/s
Testing upload speed...............................................................................................
.Upload: 1.81 Mbit/s
Share results

将提取

"2.06" #correct 
".1.81" #wrong preceding dot

答案1

正则表达式和变量太多。

获取两个值:

$ sed -n 's/^\.*\(Download\|Upload\): //p' data
2.06 Mbit/s
1.81 Mbit/s

获取一个值:

$ sed -n 's/^\.*Upload: //p' data
1.81 Mbit/s

获取一个不带“Mbit/s”的值:

$ sed -n 's/^\.*Upload: \([0-9.]*\).*/\1/p' data
1.81
  • ^\.*删除前面的点(任意数量)
  • \([0-9.]*\)用于替换的捕获组\1

相关内容