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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to edit files using Perl?

Status
Not open for further replies.

VotTak

Programmer
Sep 18, 2003
8
US
I'm newbee so please take it easy...
Basicaly I need to write a utility which would open file, match the string, substitute it and save the changes to file. Seems kind of simple but I have no clue how to save substitutes in file.

Read it line by line, substitute as necessary and save it into another file sound like too much.
I'm sure Perl got something for that. Anyone?
Thank you very much.
 
Refer to thread219-695804 , this will put you in the right direction.
 
Nah, that's not good enough... they are extracting parts of the file... I do not want to extract lines, change them and write them into another file.
I thought that there is the way to save substituted lines to the same file.
 
Files are stored as bytes, not lines, so the only way to truely edit a file inplace is to swap bytes on a one-for-one basis (seems like I've said that recently, but I couldn't find the thread). You can't change a part of a file in the middle and have everything after that part of the file shift one way or the other. Filesystems don't work that way.

Your best option is to open the original file for reading and a temp file as new. Read the original and print to temp, making changes as need be. When done, delete the original and rename the temp to its name.

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
OK...
Thank you. I was doing it the exact way you described but just thought that it might be better way.
Thanks anyway
 
You could check out Tie::File and see if that does something closer to what you're after, but I've not used it:
The rename/open/delete method is how the -i switch for perl itself works (see perlrun), so I'd say it's good enough perl.

----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Hey, icrf!!!
Thanx a lot!! WOW!! It does work the way I want. Perfect.
Apreciate your help.
 
Here is a UNIX shell script solution:

This example is where your source data is in "filename1" and you want to change all instances of "A" to "b". The changes will be permanent in "filename1".

global.sh filename1 A b

Here is the script:

global.sh
#!/bin/sh
#
# Usage is global.sh filename fromstring tostring
#
mv $1 global.1234567890.wrk
sed s/"$2"/"$3"/g global.1234567890.wrk > $1
rm global.1234567890.wrk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top