cjff150 has asked for the wisdom of the Perl Monks concerning the following question:
Hello, I'd appreciate any guidance on this -- I'm very new to PERL and can't crack this one. I have a pipe delimited file and the beginning of each line must start with | and end with || (no space in-between). Blank columns on a row should have a space inbetween the delimiters | |. I created the code below using regex to insert a space between the || delimiters anywhere a column might have blank data which is working ok.
Here's an example, the code below changes the file from:
|red||blue|yellow||black||
|white|yellow||teal||purple||
|red||black||yellow||teal||
To..(note spaces between delimiters for blank column data)
|red| |blue|yellow| |black||
|white|yellow| |teal| |purple||
|red| |black|yellow| |teal||
Here's the code
#!C:\Perl64\bin\perl -w use strict; # Iteration 1, open myfile.txt open(FILE, "</temp/PERL-Samples/myfile.txt") || die "File not found"; my @lines = <FILE>; close(FILE); #This section uses an array and scans each line and does a #sequential search and replace for the following strings: #1. Finds any instance of || and changes it to | | #2. Finds any instance of | || and changes it to | | | #3. Finds any instance of || | and changes it to | | | #4. Finds any instance of | | at the end of a line and #changes it to || my @newlines; foreach(@lines) { $_ =~ s/\|\|/\| \|/g; $_ =~ s/\| \|\|/\| \|/g; $_ =~ s/\|\| \|/\| \|/g; $_ =~ s/\| \|$/\|\|/g; push(@newlines,$_); } #Push changes to MyFileNew.dat open(FILE, ">/temp/PERL-Samples/MyFileNew.dat") || die "File not found +"; print FILE @newlines; close(FILE);
Another pre-existing condition this file has is there are several hundred lines where | and || exist on a line by themselves. Plus there are other lines not beginning with a | and ending with ||. For example:
|red| |blue|yellow| |black
||
|white|yellow| |teal| |purple||
|
red| |black|yellow| |teal
||
I'm not sure how to reliably and efficiently delete rows where || and | are the only characters in a line and also make sure each line is prefixed with | and suffixed with ||. Thanks in advance for reviewing this.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How do I delete lines matching a certain condition and make sure each line has the right prefix and suffix?
by kennethk (Abbot) on Sep 16, 2014 at 23:51 UTC | |
Re: How do I delete lines matching a certain condition and make sure each line has the right prefix and suffix?
by locked_user sundialsvc4 (Abbot) on Sep 17, 2014 at 00:09 UTC | |
by Laurent_R (Canon) on Sep 17, 2014 at 06:41 UTC |