Count and replacing strings a texfile

Mats Kindahl matkin at iar.se
Tue Jan 23 06:15:57 EST 2001


puckoh at my-deja.com writes:

> Hello.
> 
> This is a probably basic question.
> I have a textfile about 120k large, and there is several strings in it
> which I must replace.
> The strings are named "%id%" and the number of strings are unknown.
> 
> First, I need to count them all.
> Then I must replace every one of them with a incrementing number.
> Like the first %id% is replaced with 1, the second with 2 etc.
> 
> I've been told that this is a perfect job for Perl, but I don't
> understand Perl.
> I merely understand Python. Well, I think I got the basics anyway. :)
> 
> Anyone care to help me out for a minute to suggest what to do?
> Any pointers to examples are alot appreciated.

There have been Python code to do the job elswhere in the thread, but
the following Perl code (of the top of my head) will do the job you
describe and save the old files with a .old at the end. You can give
several files at the end.

perl -pi.old -e 's/%id%/++$cnt/eg; END { print $cnt,"\n" }' test.txt

Good luck,
Mats

P.S.
I am *not* trying to advocate Perl (or any other language, for that
matter). Don't take this article as anything along those lines.
D.S.

-- 
Mats Kindahl, IAR Systems, Sweden

Any opinions expressed are my own, not my company's.



More information about the Python-list mailing list