Ivan Chan
Ivan Chan

Reputation: 39

Search and replace null and dot in a column of file

I want to search and replace null and dot in a column of file using awk or sed.

The file's content is:

02-01-12 28.46
02-02-12 27.15
02-03-12 
02-04-12 27.36
02-05-12 47.57
02-06-12 27.01
02-07-12 27.41
02-08-12 27.27
02-09-12 27.39
02-10-12 .
02-11-12 27.44
02-12-12 49.93
02-13-12 26.99
02-14-12 27.47
02-15-12 27.21
02-16-12 27.48
02-17-12 27.66
02-18-12 27.15
02-19-12 51.74
02-20-12 27.37

The dots and null value can be be appeared in any rows in the file, I want to replace null and dots with the value above, say ,

02-01-12 28.46
02-02-12 27.15
02-03-12 27.15     ****** replace with the above value
02-04-12 27.36
02-05-12 47.57
02-06-12 27.01
02-07-12 27.41
02-08-12 27.27
02-09-12 27.39
02-10-12 27.39     ****** replace with the above value
02-11-12 27.44
02-12-12 49.93
02-13-12 26.99
02-14-12 27.47
02-15-12 27.21
02-16-12 27.48
02-17-12 27.66
02-18-12 27.15
02-19-12 51.74
02-20-12 27.37

Upvotes: 2

Views: 1013

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 360485

awk 'BEGIN {prev = "00.00"} NF < 2 || $2 == "." {$2 = prev} {prev = $2; print}' filename

If you have multiple columns which might have missing data:

awk 'BEGIN {p = "00.00"} {for (i = 1; i <= NF; i++) {if (! $i || $i == ".") {if (prev[i]) {$i = prev[i]} else {$i = p}}; prev[i] = $i}; print}' filename

Upvotes: 2

potong
potong

Reputation: 58508

This might work for you (GNU sed):

 sed -i '$!N;s/^\(.\{9\}\(.*\)\n.\{9\}\)\.\?$/\1\2/;P;D' file

Upvotes: 3

William Pursell
William Pursell

Reputation: 212514

$ awk -v prev=00.00 'NF<2 || $2=="." { print $1, prev; next }{prev=$2}1' input-file

Upvotes: 1

Florian Sowade
Florian Sowade

Reputation: 1747

The following awk script should work:

BEGIN {
    last="00.00"
}

{
    if ($2 != "" && $2 != ".") {
        last=$2
    }
    print $1 " " last
}

Upvotes: 1

Related Questions