Using a count variable in a file name

前端 未结 2 1412
灰色年华
灰色年华 2021-01-17 14:54

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 15:47

    Here's a quick demonstration. The touch command updates the last-modified time on the file, or creates it if it doesn't exist.

    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 $i is only one digit:

    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.

提交回复
热议问题