bash 在文件名中使用计数变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11162049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a count variable in a file name
提问by Stephopolis
I have a quick question. I just wanted to know if it was valid format (using bash shell scripting) to have a counter for a loop in a file name. I am thinking something along the lines of:
我有一个快速的问题。我只是想知道在文件名中有一个循环计数器是否是有效的格式(使用 bash shell 脚本)。我正在考虑以下方面的事情:
for((i=1; i <=12; i++))
do
STUFF
make a file(i).txt
采纳答案by Paused until further notice.
If you only want to make a bunch of files and don't need the loop for anything else, you can skip the loop altogether:
如果您只想制作一堆文件并且不需要其他任何东西的循环,您可以完全跳过循环:
touch file{1..12}.txt
will make them all in one command.
将使它们全部集中在一个命令中。
If you have Bash 4, you can get leading zeros like this:
如果你有 Bash 4,你可以得到这样的前导零:
touch file{01..12}.txt
回答by Michael Hoffman
Here's a quick demonstration. The touchcommand updates the last-modified time on the file, or creates it if it doesn't exist.
这是一个快速演示。该touch命令更新文件的上次修改时间,如果文件不存在则创建它。
for ((i=1; i<=12; i++)); do
filename="file$i.txt"
touch "$filename"
done
You may want to add leading zeroes to the cases where $iis only one digit:
您可能希望在$i只有一位数字的情况下添加前导零:
for ((i=1; i<=12; i++)); do
filename="$(printf "file%02d.txt" "$i")"
touch "$filename"
done
This will result in file01.txt, file02.txt, and so on, instead of file1.txt, file2.txt.
这将导致file01.txt, file02.txt, 等等,而不是file1.txt, file2.txt。

