3

I wrote a bash script and I did:

 num=`wc -l /tmp/file.txt | awk '{sum += $1} END {print sum}'`
 #echo $num 
 #result is for example 29
 for i in {1..$num}
 do
       touch /tmp/pages/$i.txt
 done

I want to touch 1.txt till 29.txt (echo $num ==> 29)

the result is wrong...

how can I write a correct loop like what I said...?

thank you in avanced

MLSC
  • 5,872
  • 8
  • 55
  • 89

2 Answers2

4

The problem is that brace expansion (such as {1..3,5}1 2 3 5) is performed before parameter expansion (such as $num29), so the former can't depend on the latter. In your case, one option is to use an arithmetic (C-style) for-loop:

for (( i = 1 ; i <= num ; ++i )) ; do
    touch /tmp/pages/$i.txt
done

(This is most appealing if you're used to languages where this style of for-loop is common. If you prefer foreach-loops, then ray's answer, using the external seq utility, is probably the way to go.)

ruakh
  • 175,680
  • 26
  • 273
  • 307
3

if you have seq, you can try

for i in $(seq $num)

but instead of

num=`wc -l /tmp/file.txt | awk '{sum += $1} END {print sum}'`

why don't you just

num=$(wc -l < /tmp/file.txt)

I guess you are not just touching files inside the loop
but just in case that's what you want, you can do it using awk

awk '{system("touch /tmp/pages/"NR".txt")}' /tmp/file.txt
ray
  • 4,109
  • 1
  • 17
  • 12
  • +1 for the suggestion to do it entirely in awk. Alternatively in Bourne shell, `nl file.txt | while read n _; do touch "$n".txt; done` – tripleee Jan 18 '14 at 13:54