Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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.

like image 358
pogibas Avatar asked Feb 14 '13 08:02

pogibas


2 Answers

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.

like image 200
Johnsyweb Avatar answered Sep 25 '22 20:09

Johnsyweb


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++))
like image 27
P.P Avatar answered Sep 24 '22 20:09

P.P