5

I am looping over the commands with for i in {1..n} loop and want output files to have n extension.

For example:

  for i in {1..2}
  do cat FILE > ${i}_output
  done

However n is user's input:

  echo 'Please enter n'
  read number
  for i in {1.."$number"}
  do 
    commands > ${i}_output
  done

Loop rolls over n times - this works fine, but my output looks like this {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.

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • 1
    http://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-in-bash – KBart Feb 14 '13 at 08:20

4 Answers4

9

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 number or i in the for-loop header but double-parentheses are required.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
3

The range parameter in for loop works only with constant values. So replace {1..$num} with a value like: {1..10}.

OR

Change the for loop to:

  for((i=1;i<=number;i++))
P.P
  • 117,907
  • 20
  • 175
  • 238
0

You can use a simple for loop ( similar to the ones found in langaues like C, C++ etc):

echo 'Please enter n'
read number
for (( i=1; i <= $number; i++ ))
do
  commands > ${i}_output
done
vaisakh
  • 1,041
  • 9
  • 19
-1

Try using seq (1) instead. As in for i in $(seq 1 $number).

  • `seq` involves the execution of an external command that may slow things down, but I'm not sure that warrants a downvote. – johnsyweb Feb 14 '13 at 08:37