Reputation: 85
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
Upvotes: 1
Views: 117
Reputation: 14955
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
Upvotes: 2
Reputation: 27486
Each print
is treated as a separate record, so it adds the ORS
at the end.
You can use printf
istead:
#!/bin/bash
awk ' BEGIN{
RS="|";
FS=" ";};
{
for (i=1; i<=NF ; i++)
{
if ($i == "-")
{
st=$(i-1);
en=$(i+1);
st++;
while (st < en)
{
printf "%d ", st;
st++;
}
}
else
printf "%d " $i;
}
printf "\n"
}' list.txt
Upvotes: 1