【发布时间】:2020-02-13 17:04:06
【问题描述】:
我正在尝试编写一个简单的脚本,该脚本创建五个由循环中的变量枚举的文本文件。谁能告诉我如何计算算术表达式。这似乎不起作用:
touch ~/test$(($i+1)).txt
(我知道我可以在单独的语句中评估表达式或更改循环...)
提前致谢!
【问题讨论】:
标签: shell unix terminal evaluation
我正在尝试编写一个简单的脚本,该脚本创建五个由循环中的变量枚举的文本文件。谁能告诉我如何计算算术表达式。这似乎不起作用:
touch ~/test$(($i+1)).txt
(我知道我可以在单独的语句中评估表达式或更改循环...)
提前致谢!
【问题讨论】:
标签: shell unix terminal evaluation
正确答案取决于您使用的外壳。它看起来有点像 bash,但我不想做太多假设。
您列出的命令touch ~/test$(($i+1)).txt 将正确地使用$i+1 的任何内容触及文件,但它没有做的是更改$i 的值。
在我看来你想做的是:
testn.txt 的文件中找到 n 的最大值,其中 n 是大于 0 的数字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
【讨论】: