【问题标题】:Arithmetic in shell script (arithmetic in string)shell脚本中的算术(字符串中的算术)
【发布时间】:2020-02-13 17:04:06
【问题描述】:

我正在尝试编写一个简单的脚本,该脚本创建五个由循环中的变量枚举的文本文件。谁能告诉我如何计算算术表达式。这似乎不起作用:

touch ~/test$(($i+1)).txt

(我知道我可以在单独的语句中评估表达式或更改循环...)

提前致谢!

【问题讨论】:

    标签: shell unix terminal evaluation


    【解决方案1】:

    正确答案取决于您使用的外壳。它看起来有点像 bash,但我不想做太多假设。

    您列出的命令touch ~/test$(($i+1)).txt 将正确地使用$i+1 的任何内容触及文件,但它没有做的是更改$i 的值。

    在我看来你想做的是:

    • 在名为 testn.txt 的文件中找到 n 的最大值,其中 n 是大于 0 的数字
    • 将数字递增为 m。
    • 触摸(或以其他方式输出)名为testm.txt 的新文件,其中 m 是递增的数字。

    使用here 列出的技术,您可以剥离文件名的各个部分以构建您想要的值。

    假设以下内容位于名为“touchup.sh”的文件中:

    #!/bin/bash
    # first param is the basename of the file (e.g. "~/test")
    # second param is the extension of the file (e.g. ".txt")
    # assume the files are named so that we can locate via $1*$2 (test*.txt)
    
    largest=0
    for candidate in (ls $1*$2); do
       intermed=${candidate#$1*}
       final=${intermed%%$2}
       # don't want to assume that the files are in any specific order by ls
       if [[ $final -gt $largest ]]; then
          largest=$final
       fi
    done
    
    # Now, increment and output.
    largest=$(($largest+1))
    touch $1$largest$2
    

    【讨论】:

    • 好久没来了。谢谢你的回答,帮了大忙!
    猜你喜欢
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2021-09-01
    • 2013-08-17
    相关资源
    最近更新 更多