gpt4 book ai didi

bash - 在 for 循环中创建文件名

转载 作者:行者123 更新时间:2023-11-29 09:46:04 25 4
gpt4 key购买 nike

我需要一种可以在 for 循环中使用 mkdir 生成大量目录的方法。

for i in $(seq 1 1 ${k})
do
mkdir ...
done

文件夹名称是k数字的名称,例如0_0_1,此时k = 3。

for 循环必须生成不同的名称,其中 1 的位置会发生变化。所以生成的名称和创建的目录应该是

1_0_00_1_00_0_1 对于 k = 3

也是按照这个顺序。

这可能吗?

最佳答案

纯 Bash 解决方案(不调用外部实用程序):提示 archimiro 鼓励我也在 Bash 循环中初始化数组。

# Determine the number of digits
k=3

# Create an array with the specified number of digits
# initialized to 0s (e.g., with k = 3, `( 0 0 0 )`).
arr=()
for (( i = 0; i < k; ++i )); do arr[i]='0'; done

# Loop over all digits and set each one to 1 in isolation.
IFS='_' # set IFS, the internal field separator, also used when printing arrays as strings
for (( i = 0; i < k; ++i )); do
arr[i]=1
# Inside "...", with index [*], the array elements are joined with
# the 1st char. in $IFS.
echo "${arr[*]}"
arr[i]=0
done

注意:为简洁起见,我省略了保存和恢复上面的原始 $IFS 值,这在现实世界的脚本中是可取的。

以上结果:

1_0_0
0_1_0
0_0_1

关于bash - 在 for 循环中创建文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com