1

Let file.txt be the following file

1
2
3
5
6
7
15
16
17
19
20
23
24

I was trying to write an awk command that prints the ranges of numbers that are missing. When the range includes only one number, then this number alone should be printed. The expected output is

4
8-14
18
21-22

This post pretty much did the job for me with the one liner

awk '$1!=p+1{print p+1"-"$1-1}{p=$1}' file.txt

4-4
8-14
18-18
21-22

I tried to modify it to

awk 'if ($1!=p+1){if (p+1!=$1-1) {print p+1"-"$1-1} else {print p+1} }{p=$1}' file.txt

but it does not work as expected. I seem to misunderstand the if-else grammar. What am I doing wrong?

Community
  • 1
  • 1
Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • Read the first couple of pages of the book Effective Awk Programming, 4th Edition, by Arnold Robbins to solve this problem. Then read the rest of the book :-). – Ed Morton Jul 26 '16 at 21:40

1 Answers1

3

You can use:

awk '$1 != p+1 {print p+1 ($1-1 > p+1 ? "-" $1-1 : "")} {p=$1}' file

4
8-14
18
21-22
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Sorry I forgot to check your answer (or respond to your comment). Yes it worked fine. I have already used it a lot and modified it quite a bit. Thank you! +1 – Remi.b Aug 03 '16 at 00:10