无法以算术方式评估文件中的行作为输入

无法以算术方式评估文件中的行作为输入

所以我正在编写一个 bash 脚本,它接受一个每行都有整数的文件,并且我正在编写一个函数,将每行中的这些整数转换为罗马数字,我需要将其写入另一个文件中(我将使用 > 来执行此操作) >)。大部分工作是由函数 SubValue 和 RomanCon 完成的,RomanCon 循环遍历从文件中读取的行并将其转换为罗马数字,而 subvalue 只是基本上将整数中的值替换为罗马数字。当我直接从命令行输入整数时,这两个工作正常。然而,当我尝试从文件输入中读取时,它无法正常工作,因为它一直说预期的整数表达式,尽管我的文件中的行纯粹由整数组成。我尝试过使用双括号(())和其他强制类型 -i 但是仍然没有达到我想要的效果。

谢谢

#!/bin/bash
#https://www.linuxjournal.com/content/converting-decimals-roman-numerals-bash
#https://opensource.com/article/21/3/input-output-bash
#https://phoenixnap.com/kb/bash-read-file-line-by-line
#https://www.tutorialspoint.com/linux_admin/linux_admin_reading_and_writing_to_files.htm
#https://github.com/joric/interviewbit/blob/master/scripting/regex-and-functions/convert-integer-to-roman-number.md

SubValue()
{
  # add $2 to romanvalue and subtract $1 from decvalue

  romanvalue="${romanvalue}$2"
  decvalue=$(($decvalue - $1 ))
}


RomanCon()
{
    decvalue=$1
    while [ "$decvalue" -gt 0 ] ; do
        if [ "$decvalue" -ge 1000 ] ; then
            SubValue 1000 "m"
        elif [ "$decvalue" -ge 900 ] ; then
            SubValue 900 "cm"
        elif [ "$decvalue" -ge 500 ] ; then
            SubValue 500 "d"
        elif [ "$decvalue" -ge 400 ] ; then
            SubValue 400 "cd"
        elif [ "$decvalue" -ge 100 ] ; then
            SubValue 100 "c"
        elif [ "$decvalue" -ge 90 ] ; then
            SubValue 90 "xc"
        elif [ "$decvalue" -ge 50 ] ; then
            SubValue 50 "l"
        elif [ "$decvalue" -ge 40 ] ; then
            SubValue 40 "xl"
        elif [ "$decvalue" -ge 10 ] ; then
            SubValue 10 "x"
        elif [ "$decvalue" -ge 9 ] ; then
            SubValue 9 "ix"
        elif [ "$decvalue" -ge 5 ] ; then
            SubValue 5 "v"
        elif [ "$decvalue" -ge 4 ] ; then
            SubValue 4 "iv"
        elif [ "$decvalue" -ge 1 ] ; then
            SubValue 1 "i"
        fi
    done
    echo $romanvalue
}

file=$1
while read -r line; do
    RomanCon $line
done <$file

我当前正在使用命令行参数运行脚本:

./roman.sh rome.txt

是的,我知道我没有完成对文件组件的写入,但是到目前为止,这还没有起作用,因为每当我运行它时,它都会继续输出:

: integer expression expected

: integer expression expected

: integer expression expected

: integer expression expected

因此我不知道如何获取这些输入(这是一个包含整数的文件,例如:

1111
2345
789
905

答案1

如果输入包含来自 DOS 格式文本文件的数据,则脚本通常会发出这些错误。当由 Unix shell 脚本读取时,此类文件中的每一行都将包含一些文本,例如1111,后跟一个回车符(DOS 文本文件用于编码换行符的一部分)。回车符将是line循环中读入变量的数据的一部分,因此该值不能在稍后的代码中用作整数。

使用该实用程序将您的输入转换为 Unix 文本文件dos2unix

代码的另一个问题是romanvalue变量不断与越来越多的罗马数字连接。您应该在主循环的每次迭代中重置它。

对您的代码和输入数据进行这些更改,以下将是具有给定输入的脚本的输出:

mcxi
mmcccxlv
dcclxxxix
cmv

相关内容