Thursday, February 3, 2022

[SOLVED] Adding variable amount of lines to file in Bash

Issue

I have a file with lines of a format XXXXXX_N where N is some number. For example:

41010401_1
42023920_3
45788_1

I would like to add N-1 lines before every line where N>1 such that I have lines for the specified XXXX value with all N values up to and including the original N:

41010401_1
42023920_1
42023920_2
42023920_3
45788_1

I thought about doing it with sed but I'm not sure how to conditionally append different amount of lines with different value which is based on what sed reads. Is sed even the correct command to deal with this problem?

Any help would be appreciated.


Solution

One way in is to set field separators to underscore and print all missing records when 2nd field is greater than 1 in a loop like below.

$ awk 'BEGIN{FS=OFS="_"} $2>1{for(i=1;i<$2;i++) print $1,i} 1' file
41010401_1
42023920_1
42023920_2
42023920_3
45788_1


Answered By - oguz ismail
Answer Checked By - Robin (WPSolving Admin)