I wonder if there is an efficient way to delete the first line in a file if it matches a specified pattern. For example, I have a file with data of the following form:
Date,Open,High,Low,Close,Volume,Adj.Volume
2012-01-27,42.38,42.95,42.27,42.68,2428000,42.68
2012-01-26,44.27,44.85,42.48,42.66,5785700,42.66
.
.
.
I want to delete the first line, only if it contains the text (as shown in the example in the first line), and leave it unchanged if it contains only numbers(as in the rest of the lines). This task is quite easy and I’ve accomplished it by applying the following peace of code which writes each line to a $newFile as long as it does not include Date pattern:
while( <$origFile> )
{
chomp($_);
print $newFile $_ unless ($_ =~ m/Date/g)
}
So as I mentioned, that makes the job done. However it seems that it’s a great waste of resources to read each line in a whole file when it is known that the text can appear only in the first line..
Is there any way to accomplish this task more efficiently?
NOTE: I already found an almost similar question here, but since I want my code to be available on Linux and Windows as well, using sed will not help me here.
Thanks in advance!
$.can be used to determine if are processing the first line of the file.It’s impossible to delete from anywhere but the end of a file. To delete from the start or middle, everything that follows in the file needs to be shifted, which means it must be both read and written.
You can only avoid work if the first line doesn’t match (by doing nothing at all). If you need to remove the line, you must copy the whole file.