user189035
user189035

Reputation: 5789

Replace blank value with previous non blank first column value using awk (value separated columns)

I have comma separated file with two columns where the first column is always empty and the second one is sometimes empty (when the last column is empty there is no final comma):

,value_c1_1
,,value_c2_1
,,value_c2_2
,,value_c2_3
,value_c1_2

I would like to use awk to fill empty column value with previous non-empty column value and then get rid of the rows where the second column is empty:

,value_c1_1,value_c2_1
,value_c1_1,value_c2_2
,value_c1_1,value_c2_3

The big difference with the answer to this question

awk '/^ /{$0=(x)substr($0,length(x)+1)}{x=$1}1' file

is that the fields are character separated (instead of being of fixed length) and that the first column is always empty.

Upvotes: 1

Views: 912

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753575

awk -F, 'BEGIN { OFS = FS } { if ($2 == "") $2 = last2; else last2 = $2; print }'

If column 2 is empty, replace it with the saved value; otherwise, save the value that's in column 2 for future use. Print the line. (The BEGIN block ensures the output field separator OFS is the same as the (input) field separator, FS.)

If you only want to print lines with 3 fields, then:

awk -F, 'BEGIN { OFS = FS }
         { if ($2 == "") $2 = last2; else last2 = $2; if (NF == 3) print }'

Upvotes: 2

Related Questions