Filling spaces with awk or something else

I have a list, such as below, where 1 column is the position and the other columns are not important for this question.

1 1 2 3 4 5 2 1 2 3 4 5 5 1 2 3 4 5 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 

I want to fill in the blanks so that the list is continuous and it reads

 1 1 2 3 4 5 2 1 2 3 4 5 3 0 0 0 0 0 4 0 0 0 0 0 5 1 2 3 4 5 6 0 0 0 0 0 7 0 0 0 0 0 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 

I am familiar with awk and shell scripts, but whatever the way it is, fine with me. Thanks for any help ..

+4
source share
4 answers

This single line machine may work for you:

 awk '$1>++p{for(;p<$1;p++)print p"  0 0 0 0 0"}1' file 

with your example:

 kent$ echo '1 1 2 3 4 5 2 1 2 3 4 5 5 1 2 3 4 5 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5'|awk '$1>++p{for(;p<$1;p++)print p" 0 0 0 0 0"}1' 1 1 2 3 4 5 2 1 2 3 4 5 3 0 0 0 0 0 4 0 0 0 0 0 5 1 2 3 4 5 6 0 0 0 0 0 7 0 0 0 0 0 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 
+6
source

You can use the following single-line awk:

 awk '{b=a;a=$1;while(a>(b++)+1){print(b+1)," 0 0 0 0 0"}}1' input.file 

Tested with input here-document:

 awk '{b=a;a=$1;while(a>(b++)+1){print(b+1)," 0 0 0 0 0"}}1' <<EOF 1 1 2 3 4 5 2 1 2 3 4 5 5 1 2 3 4 5 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 EOF 

The output is as follows:

 1 1 2 3 4 5 2 1 2 3 4 5 3 0 0 0 0 0 4 0 0 0 0 0 5 1 2 3 4 5 6 0 0 0 0 0 7 0 0 0 0 0 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 

Explanation:

On each line of input b , the value a , where a is the value of the first column. Due to the order in which b and a initialized, b can be used in a while , which runs as long as b < a-1 and inserts the missing rows filled with zeros. 1 at the end of the script will finally print an input line.

+1
source

This is just for fun:

 join -a2 FILE <(seq -f "%g 0 0 0 0 0" $(tail -1 FILE | cut -d' ' -f1)) | cut -d' ' -f -6 

gives:

 1 1 2 3 4 5 2 1 2 3 4 5 3 0 0 0 0 0 4 0 0 0 0 0 5 1 2 3 4 5 6 0 0 0 0 0 7 0 0 0 0 0 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 
+1
source

Here is another way:

 awk '{x=$1-b;while(x-->1){print ++b," 0 0 0 0 0"};b=$1}1' file 

Test:

 $ cat file 1 1 2 3 4 5 2 1 2 3 4 5 5 1 2 3 4 5 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 

 $ awk '{x=$1-b;while(x-->1){print ++b," 0 0 0 0 0"};b=$1}1' file 1 1 2 3 4 5 2 1 2 3 4 5 3 0 0 0 0 0 4 0 0 0 0 0 5 1 2 3 4 5 6 0 0 0 0 0 7 0 0 0 0 0 8 1 2 3 4 5 9 1 2 3 4 5 10 1 2 3 4 5 11 1 2 3 4 5 
0
source

Source: https://habr.com/ru/post/1490805/


All Articles