6

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.

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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++))

2 Comments

i <= number or you'll miss the last element. And you don't need the $ there, either (see my answer).
@Johnsyweb Fixed it. But $ doesn't hurt either :)
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

4 Comments

i <= number. No $.
@Johnsyweb, I tried that out. Seems both are working. :)
Great :-) Every day's a school-day.
Right..I learned something new too. Thanks! :)
-1

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

1 Comment

seq involves the execution of an external command that may slow things down, but I'm not sure that warrants a downvote.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.