Bash for 循环 - 以 n(用户输入)命名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14870406/
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
Bash for loop - naming after n (which is user's input)
提问by PoGibas
I am looping over the commands with for i in {1..n}loop and want output files to have nextension.
我正在使用循环遍历命令for i in {1..n}并希望输出文件具有n扩展名。
For example:
例如:
for i in {1..2}
do cat FILE > ${i}_output
done
However nis user's input:
然而n是用户的输入:
echo 'Please enter n'
read number
for i in {1.."$number"}
do
commands > ${i}_output
done
Loop rolls over ntimes - this works fine, but my output looks like this {1..n}_output.
循环滚动n时间 - 这很好用,但我的输出看起来像这样{1..n}_output。
How can I name my files in such loop?
如何在这样的循环中命名我的文件?
Edit
编辑
Also tried this
也试过这个
for i in {1.."$number"}
do
k=`echo ${n} | tr -d '}' | cut -d "." -f 3`
commands > ${k}_output
done
But it's not working.
但它不起作用。
回答by Johnsyweb
Use a "C-style" for-loop:
echo 'Please enter n'
read number
for ((i = 1; i <= number; i++))
do
commands > ${i}_output
done
Note that the $is not required ahead of numberor iin the for-loop header but double-parenthesesare required.
请注意,在-loop 标头$之前number或i中不需要 ,for但需要双括号。
回答by P.P
The range parameter in for loop works only with constant values. So replace {1..$num}with a value like: {1..10}.
for 循环中的 range 参数仅适用于常量值。所以{1..$num}用一个像这样的值替换:{1..10}。
OR
或者
Change the for loop to:
将 for 循环更改为:
for((i=1;i<=number;i++))
回答by vaisakh
You can use a simple for loop ( similar to the ones found in langaues like C, C++ etc):
您可以使用简单的 for 循环(类似于在 C、C++ 等语言中发现的循环):
echo 'Please enter n'
read number
for (( i=1; i <= $number; i++ ))
do
commands > ${i}_output
done
回答by Christian Kiewiet
Try using seq (1)instead. As in for i in $(seq 1 $number).
尝试使用seq (1)。如for i in $(seq 1 $number).

