Print previous (non zero)

Dear All,

I have file like this,

13819       32.07   1877.65
    0      481.81   2100.86
    0      789.35   2274.05
    0     4627.61   4421.36
    0     5831.52   4855.50
20844       38.68   1902.15
    0      291.02   1945.88
    0      452.57   2013.94
    0     2194.28   3191.02
    0     2680.83   3548.06
    0     3367.51   4140.27
    0     4627.61   4421.36
    0     5831.52   4855.50
27869       41.99   1942.75
    0      420.06   1999.14
    0      730.32   2073.40
    0     1014.72   2379.12
..... 
.....
.....

Desired output : if first column is 0 print previous value (not zero)

13819       32.07   1877.65
13819      481.81   2100.86
13819      789.35   2274.05
13819     4627.61   4421.36
13819     5831.52   4855.50
20844       38.68   1902.15
20844      291.02   1945.88
20844      452.57   2013.94
20844     2194.28   3191.02
20844     2680.83   3548.06
20844     3367.51   4140.27
20844     4627.61   4421.36
20844     5831.52   4855.50
27869       41.99   1942.75
27869      420.06   1999.14
27869      730.32   2073.40
27869     1014.72   2379.12
....
....

Thanks for advance.

Attila

awk '$1{v=$1}!/$1/{$1=v}1' infile

--ahamed

1 Like

Good one ahamed. I guess it can further be shortened as

awk '$1{v=$1}{$1=v}1' infile

We can still remove 3 characters from it :wink:

awk '$1{v=$1}$1=v' infile

--ahamed

so nice :slight_smile:

Hello Ahamad,

Could you please explain the command here.

Thanks,
R. Singh

There you go...

#!/bin/bash
awk '
        $1{v=$1}                #if there is a value in the first column ie $1, then store that value to the varable "v"
        !/$1/{$1=v}             #if the first column value is 0, then assign the first column with the value stored in "v" which is 
                                #basically from the previous record
        1                       #Print everything
' infile

--ahamed

1 Like