awk - Collapse sequential numbers to ranges in bash -
i trying collapse sequential numbers ranges in bash. example, if input file
1 2 3 4 15 16 17 18 22 23 45 46 47
i want output as:
1 4 15 18 22 23 45 47
how can awk or sed in single line command?
thanks help!
$ awk 'nr==1{first=$1;last=$1;next} $1 == last+1 {last=$1;next} {print first,last;first=$1;last=first} end{print first,last}' file 1 4 15 18 22 23 45 47
explanation
nr==1{first=$1;last=$1;next}
on first line, initialize variables first
, last
, skip next line.
$1 == last+1 {last=$1;next}
if line continues in sequence last, update last
, jump next line.
print first,last;first=$1;last=first
if here, have break in sequence. print out range lastly sequence , reinitialize variables new sequence.
end{print first,last}
after end of file, print final sequence.
bash awk sed collapse
No comments:
Post a Comment