Re: sed awk question

From: Arthur Corliss <acorliss@nevaeh-linux.org>
Date: Fri Jun 11 2004 - 19:56:07 AKDT

On Fri, 11 Jun 2004, David J. Weller-Fahy wrote:

> * DENNIS BYRNE <asdcb1@uaa.alaska.edu> [2004-06-11 17:41 -0800]:
> > let's say I have a file.
> > BOFa\nb'pattern'd\ne'pattern'y\nzEOF
> >
> > I want to spilt this file at 'pattern', using something like :
> > cat filename | sed s/'pattern'/EOF/
> > [snip]
> >
> > suggestions?
>
> Maybe try the command 'split' (man 1 split)?
>
> I've used that with success in the past. I believe the -p option is the
> one that you'll want.

The problem with split is that it won't handle splitting via a regex, it would
only help if the pattern is predictably at specific locations. And then you'd
have to do a round of sed on each file to remove the pattern from the split
files after that.

Here's a one-liner that will do it, which assumes your file is "test", the
pattern to replace is "foobar":

acorliss@loki:~$ cat test
a
bfoobard
efoobary
z
acorliss@loki:~$ cat test | perl -ne 'unless ($a) { $i++ ; open($a, ">file.$i"); print $a $l if defined $l; $l = undef; }; m/^(.*)(foobar)(.*)$/s; if ($2 eq "foobar") { print $a $1; close $a; $a = undef; $l = $3; } else { print $a $_ }; /.*/;'
acorliss@loki:~$
file.1 file.2 file.3
acorliss@loki:~$ cat file.*
a
bd
ey
z
acorliss@loki:~$

Obviously, if your pattern includes quotes this becomes a much harder problem
due to the shell. In that instance you would have to make a proper script.

        --Arthur Corliss
          Bolverk's Lair -- http://arthur.corlissfamily.org/
          Digital Mages -- http://www.digitalmages.com/
          "Live Free or Die, the Only Way to Live" -- NH State Motto
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Fri Jun 11 19:52:15 2004

This archive was generated by hypermail 2.1.8 : Fri Jun 11 2004 - 19:52:16 AKDT