[英]A Better Way To Write this Bash Script?
This solution (listed below) works, but it doesn't look like the most practical of solutions. 此解决方案(下面列出)有效,但它看起来并不是最实用的解决方案。 What I want to do is populate a folder with children with a name t_###_u and then fill those child directories with two files (one of which should be renamed to parent directory name and appended with a .c) Can anyone post a better, more elegant solution?
我想做的是在一个子文件夹中填充一个名称为t _ ### _ u的子文件夹,然后用两个文件填充这些子目录(其中一个文件应重命名为父目录名称,并附加一个.c)。更好,更优雅的解决方案?
for i in {1..100}
do
mkdir `printf "t_%03d_u" $i`;
cp ./templates/* `printf "t_%03d_u" $i`;
mv `printf "./t_%03d_u/template.c" $i` `printf "./t_%03d_u/t_%03d.c" $i $i`;
done
echo "Did it work?"
Thanks for any help in advance. 感谢您的任何帮助。
The most obvious way to improve the script is to assign a variable to the name you use: 改善脚本的最明显方法是为您使用的名称分配变量:
name=`printf "t_%03d" $i`
so then you can do 这样就可以了
mkdir ${name}_u
cp ./templates/* ${name}_u/
mv ./${name}_u/template.c ./${name}_u/$name.c
Bash 4. 重击4。
for num in {001..100}
do
path="t_${num}_u"
mkdir "$path"
cp ./templates/* "$path";
mv $path/template.c ./$path/t_${num}.c
done
seq -w
is hugely useful :) seq -w
非常有用:)
#!/bin/bash
for i in `seq -w 1 100`
do
mkdir t_${i}_u
cp ./templates/* t_${i}_u
mv ./t_${i}_u/template.c ./t_${i}_u/t_${i}_u.c
done
echo "Did it work?"
I'm sure it could be improved a bit further with computing the name of the directory once and re-using it, but this is nicer-enough that I'm fine stopping here. 我相信可以通过一次计算目录名称并重新使用它来进一步改善它,但这已经足够好了,我可以在这里停下来。 :)
:)
My only advice would be to set the zero padded string to a variable to ease reading: 我唯一的建议是将零填充字符串设置为变量以方便阅读:
for i in {1..100}
do
s=$(printf "%03d" $i)
mkdir t_${s}_u
cp ./templates/* t_${s}_u
mv ./t_${s}_u/template.c ./t_${s}_u/t_${s}.c
done
for i in $(seq -w 1 100); do
mkdir t_${i}_u
cp templates/* t_${i}_u
mv t_${i}_u/template.c t_${i}_u/t_${i}.c
done
haven't tested it. 还没有测试
You could save the result of the printf in a variable rather that re-doing it each time. 您可以将printf的结果保存在一个变量中,而不是每次都重新做一次。 Or just use
seq -w 1 100
to generate the numbers: 或仅使用
seq -w 1 100
生成数字:
for i in $(seq -w 1 100)
do
d=t_${i}_u
mkdir $d
cp templates/* $d
mv $d/template.c $d/t_$i.c
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.