【问题标题】:In bash, looking for a number in a txt and use it as a variable in a bash script在 bash 中,在 txt 中查找一个数字并将其用作 bash 脚本中的变量
【发布时间】:2015-04-03 23:03:50
【问题描述】:

我有一个 bash 脚本,它可以使用 process.txt 中的变量

precess.txt 格式如下:

Processing triangulated mesh.       
 => Generating   
 => Preparing    
 => Infilling   
 => Generating  
 => Exporting   
Done. Process took 0 minutes and 4.739 seconds.  
Filament required: 4849.4mm (34.3cm3).

我想将灯丝值作为变量(在本例中为 4849.4)

我不知道该怎么做。也许在 python 或 perl 中?

【问题讨论】:

    标签: python bash perl text find


    【解决方案1】:

    使用grep:

    $ NUM=$(grep -Po '(?<=Filament required: )[0-9\.]*' process.txt)
    $ echo $NUM
    4849.4
    

    【讨论】:

      【解决方案2】:

      使用pythonre

         s = """
      Processing triangulated mesh.
       => Generating
       => Preparing
       => Infilling
       => Generating
       => Exporting
      Done. Process took 0 minutes and 4.739 seconds.
      Filament required: 4849.4mm (34.3cm3)."""
      
      
      import re 
      
      print(re.findall("Filament required:\s+(\d+\.\d+)",s))
      4849.4
      

      只需打开文件并阅读:

      with open(your_file) as f:
         print(re.findall("Filament required:\s+(\d+\.\d+)",f.read()))
      4849.4
      

      【讨论】:

        【解决方案3】:

        使用awk的另一种方式

        NUM=`awk -F':' '$1~/^Filament/{split($2,a," "); gsub('/[^0-9.]/',"",a[1]); print a[1]}' process.txt`
        echo "$NUM"
        4849.4
        

        说明

        • -F':' 指定字段分隔符
        • $1 ~ /^Filament/ {...} 做了一些事情 -- 在{...} 中指出 -- 到 field1 ($1) 匹配 (~) 正则表达式的行,该正则表达式的字符串以 Filament 开头 (^)
        • split($2,a," ") 将 field2 ($2) 通过 " " 拆分为标记为 a 的数组
        • gsub('/[^0-9.]/',"",a[1]) 替换数组元素 1 中的任何字符 (a[1]),这些字符不是数字或句点 ([^0-9.]),没有任何内容 ""
        • print a[1] 打印结果

        【讨论】:

          【解决方案4】:

          使用管道:

          $ num=$(cat process.txt|grep Filament|cut -d " " -f 3|cut -d "m" -f 1)

          $ echo $num

          【讨论】:

            猜你喜欢
            • 2011-06-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-05-16
            • 2014-04-10
            • 1970-01-01
            • 2021-08-01
            • 2021-11-04
            相关资源
            最近更新 更多