Home > Back-end >  Set a fixed numerical ration between alternative sorted numbers
Set a fixed numerical ration between alternative sorted numbers

Time:02-12

So I am working on a large text file made up of rows and rows of numbers, below is just an short excerpt to help with the question, but it could even be a series of random incrementing numbers with all sorts of numerical gaps between each row.

267
368
758
936
1248
1415
1739
1917

I am looking for a way to set a fixed numerical gap between every second pair of numbers starting on the 2nd and 3rd number. such as 100 whist maintaining the numerical difference within each pair but this difference could be any number.

Such that if the numerical gap was set to 100 the above example would become:

267
368
#      gap of 100
468
646
#      gap of 100
746
913
#      gap of 100
1013
1191

would anybody know of a possible one liner to do this in terminal of a shell script. Thanks

CodePudding user response:

A little bit clumsy, but for starters this would do, I guess. It reads the list of numbers from stdin (i.e. start with cat numbers.txt or the like), then pipe it into the rest.

paste - - | {
        read -r x m;    echo $x;          echo $m
  while read -r x y; do echo $((m =100)); echo $((m =y-x)); done
}
267
368
468
646
746
913
1013
1191

Explanation: paste - - lets us read two numbers at once, so we can read line by line (two numbers). The first pair is printed out unchanged, but the subsequent pairs only serve as the base for calculating the diffrence, which is added onto a running variable, which also increments by 100 on each iteration.


Here's a rewrite as parametrized function, and without the use of paste:

addgaps() {
  read -r m; echo $m; read -r m; echo $m
  while read -r x; read -r y; do echo $((m =$1)); echo $((m =y-x)); done;
}
cat numbers.txt | addgaps 100
  • Related