【问题标题】:How to convert a number read from a file from str to int?如何将从文件中读取的数字从str转换为int?
【发布时间】:2019-10-16 07:32:04
【问题描述】:

我使用 bash,我必须读取一个包含很多行的文件

每一行都由一个数字组成。然后,对于每一行(数字),我必须检查值是否 > 80。

这是我的问题,无论我尝试什么,我总是得到:

>integer expression expected

在 if 条件之后。那是因为我用来放置行值的变量是一个字符串。

这是我的原始文件

[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81

在我的 bash 脚本中

##!/bin/bash

file=/root/temp1


while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"

这里 expr 返回错误,因为 $line 是一个字符串。我尝试过使用另一个变量

val=$(($line + 0))

if [ $val -gt 80 ]

这里的 if 条件返回“预期的整数表达式”

我也用过回声

val=$(echo "$((line /1))") 

if [ $val -gt 80 ]

我明白了

语法错误:算术运算符无效(错误标记是 ...

来自 echo 命令,当然还有 if 条件返回

需要整数表达式

【问题讨论】:

  • 您应该尝试的第一个操作是dos2unix -f inputfile,然后尝试以下解决方案。

标签: string bash shell integer


【解决方案1】:

第一个动作: dos2unix -f inputfile

第二次行动:

从输入文件可以看出它包含空行,这将导致if 比较失败。您可以在 -gt 80 检查之上进行额外检查,以确保在传递变量 $line 之前使用 if [ ! -z $line ] 不为空,或者更好的是,您可以检查以确保该行是整数,或者可能同时使用 AND .

例子:

while read line;
do
  if [[ $line =~ ^[0-9]+$ ]];then 
      if [ $line -gt 80 ];then
          echo "$line is greater then 80"
      fi
  fi
done <input_file

或者,如果你不想放空支票([ ! -z $line ]),

此外,这可以在一行中使用awk 等其他工具来完成,但这可能符合您的要求,也可能不符合您的要求。

awk 'NF && $0>80{print $0 ,"is greater then 80"}' inputfile

【讨论】:

  • awk 有效,但不符合我的要求。而对于脚本,这个“if [[ $line =~ ^[0-9]+$ ]];then”永远不会通过。所以什么也没发生,都是字符串。顺便说一句,在文件中我没有空格,只有数字,每行一个。我开始认为问题出在文件中。
【解决方案2】:

试试这个Shellcheck-clean 纯 Bash 代码:

#! /bin/bash -p

file=/root/temp1

while read -r line ; do
    (( line > 80 )) && echo "$line > 80"
done <"$file"
  • 问题中代码的问题是它不能处理空行。此代码确实处理空行,因为包含空字符串的变量在算术表达式中被视为包含零 (((...)))。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 2022-01-09
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多