Awk Print Only Continous Numbers

Hi,

i need help to print only those numbers which occur next to each other from a file.

Input:

1
2
3
9
44
45
46
77
79
80
81

Desired Output:

1
2
3
--
44
45
46
--
79
80
81

Thank you!

Hi
Try this:

$ awk '{a[j++]=$0;}END{for (i=0;i<j;i++){ if (a==a[i+1]-1 || a==a[i-1]+1)print a; else print "--";}}' file
1
2
3
--
44
45
46
--
79
80
81

Guru

1 Like

Dear Guru,

The script works but not completely, especially when if two different sets of consecutive numbers occur next to each other. For example, if i omit number '9' in this Input, then 1,2,3,44,45,46 are printed together. Can you help?

try:

|awk -v x=1 'NR==1{n=$0}
$0==n+1{length(a[x])>0?a[x]=a[x]"\n"$0:a[x]=n"\n"$0;n=$0}$0>n+1{n=$0;x++;}
END{for(i=1;i<=x;i++) print (a?a:"--")}' urfile
1 Like

Hi Yinyuemi,

As i had mentioned before, if i omit the 9 in the input file, which i may have to do at time, then the output is printed like this:

1
2
3
44
45
46
--
79
80
81

But actually the desired output even when number '9' is omitted in the file is:

1
2
3
--
44
45
46
--
79
80
81

Thank you for your support. Since I don't know much about awk any solution will be very helpful.

try:

awk -v x=1 'NR==1{n=$0}
$0==n+1{length(a[x])>0?a[x]=a[x]"\n"$0:a[x]=n"\n"$0;n=$0}$0>n+1{n=$0;x++;}
END{for(i=1;i<=x;i++) {if(a)print a"\n--"}}' file
1 Like

Perfectly works! Thanks a lot Yinyuemi!

---------- Post updated at 05:59 PM ---------- Previous update was at 05:56 PM ----------

And one more little help! Can you also tell me how can i print each consecutive set of numbers to different files.
For example:

1
2
3
--
44
45
46
--

Print each set, say to file1 and file2.
Thanks!

try:

awk -v x=1 'NR==1{n=$0}
$0==n+1{length(a[x])>0?a[x]=a[x]"\n"$0:a[x]=n"\n"$0;n=$0}$0>n+1{n=$0;x++;}
END{for(i=1;i<=x;i++) {if(a)print a"\n--">"file"++j}}' file
1 Like

Cool, Thanks!