Remi.b
Remi.b

Reputation: 18219

awk - Issues with if else statements

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?

Upvotes: 1

Views: 75

Answers (1)

anubhava
anubhava

Reputation: 784958

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

Upvotes: 3

Related Questions