Lum – Fill empty lines in specific column with values

awkcolumnstext processing

I have data of the following format:

2342 1
6473 2
7463 2
3647
2734 1
9343

The lines that do not have a value in the 2nd column are empty in that spot (i.e. there is no space, tab etc.). I am looking for a simple command that puts a '-9' in the open places of column 2.

(Basically an awk command that checks if the line is non-zero in column 2, and then add '-9' if that's the case should do it I'd say..)

Extended example (data with more columns, some of which containing missings). I only want to add '-9' to the last column (i.e. the other columns are allowed to have missings).

2342 0 12 1
6473   13 2
7463 0 14 2
3647 0  
2734 0    1
9343 0 16 

Best Answer

If your data is expressed in fixed width columns, you could do:

For the first case:

sed 's/^.\{4\}$/& -9/'

(add " -9" to lines of 4 characters).

For the second case:

sed -e '/.\{11\}/b' -e 's/$/          /;s/\(.\{10\}\).*/\1-9/'

(add up to 10 spaces and -9 to lines of less than 11 characters).

Generally, to parse lines with fixed width fields, see the FIELDWIDTHS special variable of GNU awk.

Related Question