how to replace text in files

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

how to replace text in files

Tudor Girba-2
Hi,

How would you replace a piece of text in a file with another one and persist the change on disk?

Right now, I have:

file := 'path' asFileReference
contents := file readStreamDo: #contents.
newContents := contents copyReplaceAll: 'PATTERN' with: 'TARGET'. 
file
ensureDelete; 
writeStreamDo: [ :s | s nextPutAll: newContents asString ]

Any idea to make this more concise?

Cheers,
Doru

--

"Every thing has its own flow"
Reply | Threaded
Open this post in threaded view
|

Re: how to replace text in files

Peter Uhnak


On Fri, Jun 26, 2015 at 10:56 AM, Tudor Girba <[hidden email]> wrote:
Hi,

How would you replace a piece of text in a file with another one and persist the change on disk?

Right now, I have:

file := 'path' asFileReference
contents := file readStreamDo: #contents.
newContents := contents copyReplaceAll: 'PATTERN' with: 'TARGET'. 

why not just
newContents := file contents copyReplaceAll: ...


and since we already have contents
why not also add
~~~~~~~~~~~~~~~~
AbstractFileReference>>contents: aCollection
    self writeStreamDo: [ :stream |
        stream
            resetContents;
            nextPutAll: aCollection
    ]
~~~~~~~~~~~~~~~~

And then you could do

~~~~~~~~~~~~~~~~~~~~~~~
file := 'path' asFileReference
newContents := file contents copyReplaceAll: 'PATTERN' with: 'TARGET'. 
file
ensureDelete; 
        contents: newContents
~~~~~~~~~~~~~~~~~~~~~~~

However personally I really don't like the "ensureDelete" (or FileStream forceNewFileNamed: aFileName do: [ :stream | ... ],
and I got burned by it couple of times when I forgot about it... easy way to corrupt your files.

I mean, what is the use-case of overriding just the beginning? In most languages the default is write (override whole file) and append (add at the end)... and if you need fine control then you fseek().

This is maybe so each write to the stream doesn't reset it? What about clearing just on the first write to the stream?

Peter