制作文件的多个副本与shell脚本 [英] Make multiple copies of files with a shell script
问题描述
我试图写一个小的shell脚本,使一个文件的多个副本。我能够采取的文件名作为输入而不是拷贝数。下面是我写的。但我无法将 NUMBER
变量传递给for循环。
呼应-n输入文件名:
阅读FILENAME
要进行份数:回声-n
阅读次数
因为我在{2 .. $ NUMBER}
做
CP -f $ FILENAME $ {FILENAME %%。*}_$ i.csv
DONE
不幸的是它不喜欢的工作。巴什进行参数扩展前括号扩展,所以你会撑在 $数量扩展
进行评估。又见猛砸陷阱#33 的,这也解释了这个问题。
要做到这一点,使用code的方法之一,是:
因为我在$(EVAL回声{2 .. $ NUMBER})
做
#...
DONE
或者更短:
因为我在$(SEQ $ 2号)
#...
(感谢,格伦·杰克曼!)
请注意,通常,变量应该被引用。这是为文件名尤其重要。如果你的文件名为富栏
?那么你的 CP -f
将复制富
和栏
自参数通过空格分割。
那么,做这样的事情:
CP -f$ FILENAME$ {FILENAME %%。*} _ $ {I}的.csv
而如果你的文件不包含空格,引用变量可能并不重要的东西,你应该在将来会自动做prevent任何惊喜。
I am trying to write a small shell script that makes the multiple copies of a file. I am able to take the file name as input but not the number of copies. Here is what I wrote. But I am unable to pass the NUMBER
variable to for loop.
echo -n "Enter filename: "
read FILENAME
echo -n "Number of copies to be made: "
read NUMBER
for i in {2..$NUMBER}
do
cp -f $FILENAME ${FILENAME%%.*}"_"$i.csv
done
Unfortunately it doesn't work like that. Bash performs brace expansion before parameter expansion, so your brace will be expanded before $NUMBER
is evaluated. See also the Bash Pitfall #33, which explains the issue.
One way to do this, using your code, would be:
for i in $(eval echo {2..$NUMBER})
do
# ...
done
Or, even shorter:
for i in $(seq 2 $NUMBER)
# ...
(thanks, Glenn Jackman!)
Note that typically, variables should be quoted. This is especially important for file names. What if your file is called foo bar
? Then your cp -f
would copy foo
and bar
since the arguments are split by whitespace.
So, do something like this:
cp -f "$FILENAME" "${FILENAME%%.*}_${i}.csv"
While it might not matter if your files don't contain whitespace, quoting variables is something you should do automatically to prevent any surprises in the future.
这篇关于制作文件的多个副本与shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!