Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern Matching

Status
Not open for further replies.

drkestrel

MIS
Sep 25, 2000
439
GB
I want to replace all lines in a file with just ,(comma) to be null,
i.e.

, <linefeed>
,<linefeed>
,<linefeed>
, <linefeed>


I tried
Code:
$aString=~ s/^\s*?,\s*?$/null,/g;
$aString=~ s/^\s?,\s?$/null,/g;

but no luck!
 
you don't need the '?' in it, but that doesn't matter. i tested both your first regex and the one i have here many times with a dummy file, and it worked perfectly. here's mine:[tt]
while (<FILE>) {
s~^\s*,\s*$~null,~;
print;
}[/tt]

it may be that the problem isn't the regex, but the way you're calling it...
sorry i couldn't help any more. &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
This replaces the comma lines with the value of null, not the string. If you want the string, just put 'null' in the right side. The way you were approaching the pattern match, the '^' and '$' pinned the match to the beginning and end of the file...... not the beginning and end of a line. So, just treat the '\n' as any other character and match it. Like this,

#!/usr/local/bin/perl
$lines = `cat junk.txt`;
$lines =~ s/\s*?,\s*?\n//g;
print &quot;lines - $lines&quot;;


Where junk.txt looks like,
,
,
,
some, text,
,



HTH


keep the rudder amid ship and beware the odd typo
 
I found out that I need to use the /gm switch.
Don't quite know exactly what the /m is, but I suspect there is a Windows/UNIX linefeed problem. I used UltraEdit, and even saving test file as UNIX format did not work without the /m switch?

I guess you guys must have tried my script out in UNIX/Linux?
 
/m specifies that the match be done with multi-line behavior. were you reading the file in one line at a time, and checking that against the regex, or did you read in the file as one scalar variable, and then test that? &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
the $scalarVar contains the whole file, does it mean I need to us /m?? Not quite sure about the meaning of mult-line!
 
yes, then use /m. it has to do with how it defines certain things, like &quot;.&quot; and &quot;$&quot;, specifically whether or not they'll match on a newline. basically, if there's more than one line of text in the pattern to be matched, specifiy /m and and use the regex like usual, and i should work like usual.
&quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top