Perl: Match part of a line and replace with another line from the same file
Hi,
I need to match and manipulate particular lines of data files. You can see the shortened sample file below. The actual contains data for every day for all 12 months. The weather data that was not measured for whatever reason is input as 9999 or 999 so that the user knows that data is missing. Unfortunately, these data points cause the simulation software I'm using to crash. What I would like to do is write a perl script that will open any *.cw2.a file, read it in, find the lines that have 9999 and replace them with the first line above which does not have 9999 in it and is not a day and month demarcation line or white space etc... I've done a little bit of matching and batch processing with perl and awk but I'm unsure how to proceed with the specific line I/O. Any help is greatly appreciated. Code:
*CLIMATE |
Code:
awk '{if( NF==6 && $0 !~ /9999/){hold=$0};if(NF==6 && $0 ~ /9999/){$0=hold};print}' climate Ugly awk hack ... works on your sample data; will fail if the first line of actual data has 9999 in it. Cheers, Tink |
I don't quite get what the replacement is???
illustrate using your example. oops:simultaneous post tinkster |
Using GNU sed:
This fails if the first data line contains '9999'. (It turns an initial run of '9999' lines into empty lines). Code:
data='\([[:blank:]]\+[-0-9]\+\)\{6\}' The default line is used instead of an empty line to replace any initial '9999' lines. Code:
default=' 39 -179 130 36 70 79' Normally sed treats multiple input files as one continuous file but with '-i' they are treated as being separate. |
Code:
awk '$2!~/999/&&!/day|month/{h=$0}$2 ~/999/{ print h;next}1' file Code:
while (<>) { |
Quote:
Code:
$ grep -Hn "9999" ottawanrc_2001.cw2.a Code:
awk '$2!~/999/&&!/day|month/{h=$0}$2 ~/999/{ print h;next}1' ottawanrc_2001.cw2.a Code:
#!/usr/bin/perl |
For the awk parts just wrap it up like so.
Code:
awk '{if( NF==6 && $0 !~ /9999/){hold=$0};if(NF==6 && $0 ~ /9999/){$0=hold};print}' climate > tmp && mv tmp climate |
Quote:
|
Okay, thanks again everyone for all your help. I thought that it would edit the file in place but now I understand.
Cheers! |
All times are GMT -5. The time now is 09:38 PM. |