in reply to How to look for patterns in a file and create a CR

{ local $_= <DATA>; while( defined $_ ) { chomp; s/(.)G57/$1\nG57/g; print $1 if s/(.*\n)//s; if( ! /G5?$/ ) { print $_,$/ if "" ne $_; $_= <DATA>; } else { my $next= <DATA>; last unless defined $next; $_ .= $next; } } print $_,$/; } __END__ dasdfdafdsfadfdfaG57ewefdsfsdfsG 57dfadfasdfasdfsffdasG57dfsafdsf sG57dfafdafdsfadfafdfasdfasdfasf dafdfasdfasdfdsafasdfsdafasdfads dfadfasfdsdfadfasdfasfdadsfasfdd G57dsafdsfasdfadsfasdfadfadfadff dfdf

This produces:

dasdfdafdsfadfdfa G57ewefdsfsdfs G57dfadfasdfasdfsffdas G57dfsafdsf s G57dfafdafdsfadfafdfasdfasdfasf dafdfasdfasdfdsafasdfsdafasdfads dfadfasfdsdfadfasdfasfdadsfasfdd G57dsafdsfasdfadsfasdfadfadfadff dfdf
rather than what you asked for because it doesn't "join" lines unless it has to in order to match the string.

Update: This node briefly showed incorrect code because I forgot to paste the tested code back in.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re: How to look for patterns in a file and create a CR
by juo (Curate) on Mar 21, 2001 at 14:44 UTC

    This didn't make it work completely. I have found the way to do it. First I remove all the returns and make one file of it. After that I build in again returns looking for a certain pattern. If somebody can make it <CR> shorter and knows how I can skip to make intermediate file and create straigt away the target file it is welcome. Pieter Here is the code :

    #!perl -w use strict; use FileHandle; my $file = "c:/perl/training/test/common.grb"; #source file my $file1 = "c:/perl/training/test/test5.txt"; #intermediate file, jus +t contain one long line my @users = readFile($file); for(@users) { chomp; s/\s+/ /g; } writeFile("c:/perl/training/test/test5.txt", @users); my @newUsers = readFile($file1); for (@newUsers) { s/(.)G57/$1\nG57/g; } writeFile("c:/perl/training/test/test6.txt", @newUsers);> #target fil +e, each line start with G57 sub readFile { my ($fileName) = @_; sysopen(F, $fileName, O_RDONLY) or die "\nCannot open #<CR> $file: $!\ +n"; my @fileContents = <F>; close(F); return @fileContents; } sub writeFile { my ($file, @contents) = @_; if(-e $file) { unlink $file or die "\nunable to remove $file: $!\n"; } sysopen(F, $file, O_RDWR | O_EXCL | O_CREAT, 0666) or die "\nCannot cr +eate $file: $!\n"; print F @contents or die "\nCannot write to $file: $!\n"; close(F) or die "\nCannot close filehandle - $file: $!\n"; }

    Edit 2001-03-21 by mirod: added code tags