3

I want an array containing the numbers from 1 to twice the number of lines in a text file. In this example, the file somefile.dat has four lines. I tried:

~$ echo {1..$(( `cat somefile.dat | wc -l`*2 ))}
{1..8}

which is not what i wanted. However, what goes on inside the parenthesis has clearly been interpreted as integers. Why then, is the total result a string? And how do I convert it to an int so that I get the numbers 1 to 8 as output?

6
  • Consider using wc -l < file to get the number directly. So can you do val=$(wc -l < file). Commented Sep 26, 2014 at 16:16
  • Works in zsh. Just sayin', Commented Sep 26, 2014 at 16:17
  • cat somefile.dat | wc -l | perl -nle'for(1..$_*2){print;}' Commented Sep 26, 2014 at 16:17
  • cat somefile.dat somefile.dat | wc -l Commented Sep 26, 2014 at 16:34
  • If the only thing you are going to do is iterate over the array, it's probably going to be simpler to just use a for((i=1; i<=$(wc -l <somefile.dat)*2; i++)) loop Commented Sep 26, 2014 at 16:48

1 Answer 1

4

Why then, is the total result a string?

That is because brace range directive in shell {1..10} doesn't support a variable in it.

As per man bash

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

Examples:

echo {1..8}
1 2 3 4 5 6 7 8

n=8
echo {1..$n}
{1..8}

Alternatively you can use seq:

seq 1 $n
1
2
3
4
5
6
7
8
Sign up to request clarification or add additional context in comments.

2 Comments

OP has accepted this answer, but I don't see how it solves the problem. How do you convert a string to an integer when you need to read the contents of it as an integer?
I have added root cause for the problem OP is facing Brace expansion is performed before any other expansions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.