1

I want to create an array from a list of words. so, i'm using this code:

for i in {1..$count} 
do
array[$i]=$(cat file.txt | cut -d',' -f3 | sort -r | uniq | tail -n ${i})
done

but it fails... in tail -n ${i}

I already tried tail -n $i, tail -n $(i) but can't pass tail the value of i

Any ideas?

2
  • where do you set the value for $count? Good luck. Commented Oct 8, 2014 at 15:00
  • 1
    You could say for i in $(seq $count). Commented Oct 8, 2014 at 15:17

4 Answers 4

1

It fails because you cannot use a variable in range directive in shell i.e. {1..10} is fine but {1..$n} is not.

While using BASH you can use ((...)) operators:

for ((i=1; i<=count; i++)); do
   array[$i]=$(cut -d',' -f3 file.txt | sort -r | uniq | tail -n $i)
done

Also note removal of useless use of cat from your command.

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

3 Comments

If i replace <tail -n $i> for <sed '$i!d'> the script fails!
Better to show complete command line so that I can help better.
i think i solved it... i was doing <cut -d',' -f3 file.txt | sort -r | uniq | sed -n '$ip'> and it didn't work. tried <cut -d',' -f3 file.txt | sort -r | uniq | sed -n "$i p"> and seems to work fine. thanks a lot!
1

Your range is not evaluated the way you are thinking, e.g.:

$ x=10
$ echo {1..$x}
{1..10}

You're better off just using a for loop:

for ((i = 1; i <= count; i++))
do
   # ...
done

Comments

1

Just to elaborate on previous answers, this occurs because the 'brace expansion' is the first part of bash's parsing, and never gets repeated: when the braces are expanded, the '$count' is just a piece of text and so the braces are left as is. Then, when '$count' is expanded to a number, the brace expansion never runs again. See here.

If you wanted for some reason to force this brace expansion to happen again, you can use 'eval':

replace the {1..$count} with $(eval echo {1..${count}})

Better, in your case, to do as anubhava suggests.

Comments

1

Instead of reading the file numerous times, use the built-in mapfile command:

mapfile -t array < <(cut -d, -f3 file.txt | sort -r | uniq)

1 Comment

Although it's only implicit in the question, I think the intent is ... sort -ur | head -n $count to get only $count values. But who knows? Anyway, +1.

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.