473,804 Members | 4,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace string in existing file

I am trying to replace the word "test" in a file with the word
"Change" without creating a new file using the following code:

#! /usr/bin/perl -w

open (IN, "+</path/to/file/test.html");

while (<IN>){
s/test/Change/;
print IN;
}

close IN;

The orignal file contains:

test 1

test 2

test 3

and my results are:

test 1

test 2

test 3
test 1
Change 1
test 3
Change 3

I am looking for the results to be:

Change 1

Change 2

Change 3

and that is what I get if I output the print to a new file or to
<STDOUT>.

What am I doing wrong? Any help would be much appreciated.

Thanks in advance
Jul 19 '05 #1
4 45998
you need remember and reset the file pointer before writing out the
result, right before "print IN".
#! /usr/bin/perl -w

open (IN, "+</path/to/file/test.html");

while (<IN>){
s/test/Change/;
print IN;
}

close IN;


--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 4:58pm up 2 days 18:52 load average: 1.00 1.00 1.00
Jul 19 '05 #2
Rich wrote:
I am trying to replace the word "test" in a file with the word
"Change" without creating a new file using the following code:

open (IN, "+</path/to/file/test.html");
while (<IN>){
s/test/Change/;
print IN;
}
close IN;


The obvious problem is that you're not using seek().

The not so obvious problem is that you're doomed to failure if the
file is longer than the standard I/O buffer.

If the input is like "test 19\n", then you'll be changing eight
character lines to ten character lines. After processing four
lines (32 bytes), you will have written four lines (40 bytes), and
the fifth line read will consist of nothing but overwritten bytes.

You may have to consider reading the entire file into memory,
performing the changes, seek to the beginning, print the data
all at once, and truncating the file to size (if it got smaller).
-Joe
Jul 19 '05 #3
df***@bee.net (Rich) wrote in message news:<eb******* *************** ****@posting.go ogle.com>...
I am trying to replace the word "test" in a file with the word
"Change" without creating a new file using the following code:

#! /usr/bin/perl -w

open (IN, "+</path/to/file/test.html");

while (<IN>){
s/test/Change/;
print IN;
}

close IN;

The orignal file contains:

test 1

test 2

test 3

and my results are:

test 1

test 2

test 3
test 1
Change 1
test 3
Change 3

I am looking for the results to be:

Change 1

Change 2

Change 3

and that is what I get if I output the print to a new file or to
<STDOUT>.

What am I doing wrong? Any help would be much appreciated.

Thanks in advance

Thank you both for the tips. I was not aware of the seek() function
and I am currently trying to learn how to use it correctly but I think
I'm on the right track. I will post my results.

Thanks - Rich
Jul 19 '05 #4
df***@bee.net (Rich) wrote in message news:<eb******* *************** ****@posting.go ogle.com>...
I am trying to replace the word "test" in a file with the word
"Change" without creating a new file using the following code:

#! /usr/bin/perl -w

open (IN, "+</path/to/file/test.html");

while (<IN>){
s/test/Change/;
print IN;
}

close IN;

The orignal file contains:

test 1

test 2

test 3

and my results are:

test 1

test 2

test 3
test 1
Change 1
test 3
Change 3

I am looking for the results to be:

Change 1

Change 2

Change 3

and that is what I get if I output the print to a new file or to
<STDOUT>.

What am I doing wrong? Any help would be much appreciated.

Thanks in advance

Got it! I had to hold the text in an array first though.

#! /usr/bin/perl -w

open (IN, "+</path/to/file/test.html");

@file = <IN>;

seek IN,0,0;

foreach $file (@file){
$file =~ s/test/Change/g;
print IN $file;
}
close IN;
Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
19577
by: Niels Bosboom | last post by:
Hi! I am using PHP4.3.3 on a windows XP platform. I am building a small program that will allow my students to subscribe and unsubscribe from a service that will let them know when new results of their exams are added to the webpage of school. Since I am not allowed to use mySQL as a database, I am using a simple flat text-file to store the emailadresses submitted by my students. I can already add addresses to the file, even after I...
2
25182
by: Nico Grubert | last post by:
Hi there, I would like to open an existing file that contains some lines of text in order to append a new line at the end of the content. My first try was: >>> f = open('/tmp/myfile', 'w') #create new file for writing >>> f.writelines('123') #write first line >>> f.close()
1
1733
by: Neil Zanella | last post by:
Hello, The MSDN documentation does not seem to mention whether the Replace string method returns a new string or modifies the existing string in place and then returns it. I would like to know which is correct. Thank you, Neil
0
3085
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not want to replace all of them. You need to look at it in a case-by-case basis. What can you do? Answer: emacs.
1
1649
by: nasirmajor | last post by:
Dear all i have the following code for writing to the existing file. =========================== void AppendToFileEng() { SqlDataReader gr = null; string engpath2=""; gr = db.GetReader("Select * from tbl_SubCat2 Where SId2=" + SId2 + "");
1
2115
by: shapper | last post by:
Hello, I have a XLST file where I have the phrase "HERE". Something like: <xsl:text>HERE</xsl:text> I want to replace "HERE" by "UPDATED" and save the file.
3
16929
by: TOXiC | last post by:
Hi everyone, First I say that I serched and tryed everything but I cannot figure out how I can do it. I want to open a a file (not necessary a txt) and find and replace a string. I can do it with: import fileinput, string, sys fileQuery = "Text.txt" sourceText = '''SOURCE'''
3
14579
by: mouac01 | last post by:
Newbie here. How do I do a find and replace in a binary file? I need to read in a binary file then replace a string "ABC" with another string "XYZ" then write to a new file. Find string is the same length as Replace string. Here's what I have so far. I spent many hours googling for sample code but couldn't find much. Thanks... public static void FindReplace(string OldFile, string NewFile) { string sFind = "ABC"; //I probably need...
5
2588
by: Unknown | last post by:
Hi, I've got this code : cb = open("testfile", "r+") f = cb.readlines() for line in f: rx = re.match(r'^\s*(\d+).*', line) if not rx: continue else:
1
1980
by: mukeshrasm | last post by:
Hi I want to delete or replace the existing file from directory using PHP. I don't want to rename the file.
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10320
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.