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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:33:51  来源:igfitidea点击:

Bash for loop - naming after n (which is user's input)

bash

提问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:

使用“C 风格” 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 标头$之前numberi中不需要 ,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).