Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

bash - Finding gaps in sequential numbers

I don’t do this stuff for a living so forgive me if it’s a simple question (or more complicated than I think). I‘ve been digging through the archives and found a lot of tips that are close but being a novice I’m not sure how to tweak for my needs or they are way beyond my understanding.

I have some large data files that I can parse out to generate a list of coordinate that are mostly sequential

5
6
7
8
15
16
17
25
26
27

What I want is a list of the gaps

1-4
9-14
18-24

I don’t know perl, SQL or anything fancy but thought I might be able to do something that would subtract one number from the next. I could then at least grep the output where the difference was not 1 or -1 and work with that to get the gaps.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With :

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

explanations

  • $1 is the first column from current input line
  • p is the previous value of the last line
  • so ($1!=p+1) is a condition : if $1 is different than previous value +1, then :
  • this part is executed : {print p+1 "-" $1-1} : print previous value +1, the - character and fist columns + 1
  • {p=$1} is executed for each lines : p is assigned to the current 1st column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...