Finding gaps in sequential numbers

后端 未结 6 1086
粉色の甜心
粉色の甜心 2020-12-05 09:31

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 tip

6条回答
  •  日久生厌
    2020-12-05 10:26

    Given input file, use the numinterval util and paste its output beside file, then munge it with tr, xargs, sed and printf:

    gaps() { paste  <(echo; numinterval "$1" | tr 1 '-' | tr -d '[02-9]') "$1" | 
             tr -d '[:blank:]' | xargs echo | 
             sed 's/ -/-/g;s/-[^ ]*-/-/g' | xargs printf "%s\n" ; }
    

    Output of gaps file:

    5-8
    15-17
    25-27
    

    How it works. The output of paste <(echo; numinterval file) file looks like:

        5
    1   6
    1   7
    1   8
    7   15
    1   16
    1   17
    8   25
    1   26
    1   27
    

    From there we mainly replace things in column #1, and tweak the spacing. The 1s are replaced with -s, and the higher numbers are blanked. Remove some blanks with tr. Replace runs of hyphens like "5-6-7-8" with a single hyphen "5-8", and that's the output.

提交回复
热议问题