Shell脚本中的算术(字符串中的算术)

问题描述 投票:0回答:1

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

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

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

提前感谢!

shell unix terminal evaluation
1个回答
0
投票

正确的答案取决于您使用的外壳。它看起来有点像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
© www.soinside.com 2019 - 2024. All rights reserved.