0

I'm trying to create a sequence of numbers in bash. I found that for very long sequences, using loops written into awk is much faster and time efficient than the conventional loop with for; do; (sequence); done For example, if I have 5 samples, and I want to create a time sequence starting from 0 s with an increment of 0.5 s between each sample, with awk I just write:

awk 'BEGIN {time=0; print time; for (i=1; i<5; ++i) {time += 0.5; print time}}'

And it works ... Now, I'm trying to use this command inside a script that automates the generation of several times sequences, where some of them have different number of points and different increments. So, I need to define previously some variables that are created based on the characteristics of each data set, and then use them inside awk. Something like this (applied to the previous example):

start=1
end=5
increment=0.5
awk 'BEGIN {time=0; print time; for (i=$start; i<$end; ++i) {time += $increment; print time}}'

But that does not work ... Obviously, it is a problem of syntax. I don't know the correct way to write this. I would appreciate a lot any suggestion.

Carlos Herrera
  • 165
  • 1
  • 1
  • 7

1 Answers1

1

Use the -v syntax to add the variables in awk, in the example below using the syntax I have imported the bash variables of the same name.

awk -v start="$start" -v end="$end" -v increment="$increment" 'BEGIN {time=0; print time; for (i=start; i<end; ++i) {time += increment; print time}}'
0
0.5
1
1.5
2

You can also directly adopt the variable values as

awk -v start=1 -v end=5 -v increment=0.5 'BEGIN {time=0; print time; for (i=start; i<end; ++i) {time += increment; print time}}'
0
0.5
1
1.5
2
Inian
  • 80,270
  • 14
  • 142
  • 161