olivia olivia - 5 months ago 13
Bash Question

Print variables separated by "-" using awk

I am trying to print all numbers between two values separated by "-".
I have a document with multiple rows looking like this:

14 - 19 |
45 - 50 |


I want to have a result like:

14 15 16 17 18 19
45 46 47 48 49 50


But I keep getting all the values in the same row, although I have set ORS and OFS.

Is there anything I might be missing?

#!/bin/bash
awk ' BEGIN{OFS=" ";
RS="|";
FS=" ";
ORS=" "};
{
for (i=1; i<=NF ; i++)
{
if ($i == "-")
{
st=$(i-1);
en=$(i+1);
st++;
while (st < en)
{
print st;
st++;
}
}
else
print $i;
}
}' list.txt

Answer

If the fields are fixed, this is much more simple and direct:

$ awk '{for (i=$1+0;i<=$(NF-1);i++){printf "%d ", i};print ""}' list.txt
14 15 16 17 18 19 
45 46 47 48 49 50

To prevent trailing space (thanks @fedorqui):

awk '{for (i=$1+0;i<$3+0;i++){printf "%d ", i};print ""$3}' list.txt