Go Linux bash环境下 字符串strings.Trim截取无效
result := "40%" if len(result) > 0 { fmt.Println("result:", result) numStr := strings.TrimSpace(strings.Trim(result, "%")) fmt.Println("numStr:", numStr) numFloat, err := strconv.ParseFloat(numStr, 4) if err != nil { fmt.Printf("strconv.ParseFloat Error:%v", err) } fmt.Println("float num:", numFloat) }
Linux 下报错 strconv.ParseFloat Error:strconv.ParseFloat: parsing "40%": invalid syntaxfloat num: 0
仔细查看输出:要去掉的%没有去除成功
result: 33% numStr: 33% strconv.ParseFloat Error:strconv.ParseFloat: parsing "33%": invalid syntaxfloat num: 0
测试解决方法: 字符串后面加一个换行符\n 解决
numStr := strings.TrimSpace(strings.Trim(result, "%\n"))
package main import ( "fmt" "os/exec" "strconv" "strings" ) func main() { arg := "fping -C10 -p100 -b32 -t3000 -i100 8.8.8.8 | tail -n 1 | awk '{print $10}'" //arg := "fping -C10 -p100 -b32 -t3000 -i100 114.114.114.114 | tail -n 1 | awk '{print $10}'" // bash -c "fping -C10 -p100 -b32 -t3000 -i100 114.114.114.114 | tail -n 1 | awk '{print $10} //cmd := exec.Command("/bin/sh", "-c", arg) cmd := exec.Command("/bin/bash", "-c", arg) out, err := cmd.Output() if err != nil { fmt.Println(err) } result := string(out) if len(result) > 0 { fmt.Println("result:",result) numStr := strings.TrimSpace(strings.Trim(result,"%\n")) fmt.Println("numStr:",numStr) numFloat, err := strconv.ParseFloat(numStr, 4) if err != nil { fmt.Printf("strconv.ParseFloat Error:%v", err) } fmt.Println("float num:", numFloat) } }
posted on 2023-02-04 22:34 zhangmingda 阅读(53) 评论(0) 编辑 收藏 举报