473,666 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replacing text in a text file

1 New Member
I needed to replace some text in several string in a CSV file, so what I did was, I opened the original file as a TextStream using the FileSystemObjec t (set a reference to Microsoft Scripting Runtime). I also created a new empty text file. Now I walk through the original file and write a copy of each line out to my new text file. If I come to a line with the string I'm searching for, I write the corrected new line of text into my new text file.

Keep going to the end of the text file(s). When you're done, save the new text file, delete the original file, and rename the new file to the old one's filename. (I didn

To explain the sample code below, I was searching for a particular string (in this case I was looking for lines like this:

,,R01,222,14876 .56,,,,,,

where I wanted to add a dollar sign to the 5th field (14876.56)





Expand|Select|Wrap|Line Numbers
  1.     Dim FSO              As Scripting.FileSystemObject
  2.     Dim tsFix            As Scripting.TextStream
  3.     Dim tsOrig           As Scripting.TextStream
  4.     Dim str_TextLine     As String
  5.     Dim str_TempFile     As String
  6.     Dim as_Items()       As String
  7.     Dim str_OutgoingText As String
  8.     Dim lng_ItemNum      As Long
  9.  
  10.  
  11. Set FSO = New Scripting.FileSystemObject
  12.     If FSO.FileExists(str_SavedCSVFileName) Then
  13.         ' open a new (temp) file
  14.         str_TempFile = "TMP_" & str_SavedCSVFileName
  15.         Set tsFix = FSO.CreateTextFile(str_TempFile, True)
  16.         ' open original CSV file
  17.         Set tsOrig = FSO.OpenTextFile(str_SavedCSVFileName)
  18.             Do Until tsOrig.AtEndOfStream
  19.                 str_TextLine = tsOrig.ReadLine
  20.                     If Len(str_TextLine) > 2 And Len(str_TextLine) < 40 Then
  21.                         ' should be a Totals line as below:
  22.                         ' find 4th comma
  23.                         as_Items = Split(str_TextLine, ",")
  24.                             For lng_ItemNum = LBound(as_Items) To UBound(as_Items)
  25.                                 ' when we find the 4th comma, if the next char is a number, we'll add a $ in front of it
  26.                                 If lng_ItemNum = 4 And IsNumeric(as_Items(lng_ItemNum)) Then
  27.                                     ' this should be a dollar value
  28.                                     If InStr(as_Items(lng_ItemNum), ".") Then
  29.                                         str_OutgoingText = Replace(str_TextLine, as_Items(lng_ItemNum), "$" & as_Items(lng_ItemNum))                                                                            End If
  30.                                 End If
  31.                                 DoEvents
  32.                             Next
  33.                         ' write out contents of original CSV file but replace line above with one containing $
  34.                         tsFix.WriteLine Replace(str_TextLine, as_Items(lng_ItemNum), "$" & as_Items(lng_ItemNum))
  35.                     Else
  36.                         ' write out contents of original CSV file as is
  37.                         tsFix.WriteLine str_TextLine
  38.                     End If
  39.                 DoEvents
  40.             Loop
  41.     End If
  42.  
  43.     tsOrig.Close
  44.     Set tsOrig = Nothing
  45.     tsFix.Close
  46.     Set tsFix = Nothing
  47.     If FSO.FileExists(str_TempFile) Then
  48.         FSO.CopyFile str_TempFile, str_SavedCSVFileName, True
  49.     End If
  50.  
  51.  
Dec 29 '11 #1
0 4112

Sign in to post your reply or Sign up for a free account.

Similar topics

6
1943
by: pankaj.khandelwal | last post by:
Hi, How can I bundle a text/gif file in the shared object. Basically I want to read the content of this text file but I cannot have it seperately on the disc. Any clues. ? Pankaj
1
4554
by: David Dvali | last post by:
How can I load text from file to TextBox?
1
2156
by: Suresh Tri | last post by:
Hi, I was trying to overload concat operator ||(text,text) such a way that it behaves like Oracle. i.e. I want 'abc' || null to return 'abc' instead of null. I know that it is not the expected behaviour in postgres, but since I am migrating the database from oracle to postgres , I need this behaviour. But when I try to drop the existing || operator, I get the following
2
7443
by: Johann Robette | last post by:
Hi, I'm trying to call the array_to_string function like this : SELECT array_to_string(array, '~^~') --> it comes directly from the doc. I get this error msg : ERROR: parser: parse error at or near ", text) does not exist Unable to identify a function that satisfies the given argument types
4
1966
by: David Garamond | last post by:
What is "text + text" supposed to do right now? It doesn't seem very useful to me. What about making "text + text" as an equivalent for "text || text"? Most strongly-typed programming languages do this. And MS SQL Server too, I think (CMIIW). -- dave ---------------------------(end of broadcast)---------------------------
9
24744
by: Prakash Singh Bhakuni | last post by:
am replacing the default "Browse..." button for input type=file. This works fine except that the form will only submit after the SUBMIT button is clicked twice. Any ideas on why this is happening or a workaround? I'm testing on IE Thanks! <html> <head></head> <body> <form name="test_form" method="post" action="test.jsp">
0
1641
by: PRITPAL | last post by:
Hi There, I want a code for Saving and Reading formatted text (RTF File) in MS Access using ole Objects, i want to save 20 such records in DB using VB 6.0. Plz Help
2
1927
by: shireen Eason | last post by:
How to create a text output file from access database?
9
19089
by: xtremebass | last post by:
hi every one. i am new to this forum. i have two doubts. one is , is it possible to read a text/html file in Jsp? if so, how can we find out the end of each line in the text/html file? please help me..
3
1800
dlite922
by: dlite922 | last post by:
Hey guys, I need to maintain short list of messages in a text log file. I was just googling for the best way to delete the first or last line and insert a new one. Basically with each access I'll delete a line from the top (or bottom could work too) and insert a new line at the other end. (so it scrolls basically) If your curious, this is the status of a daily cron job, I basically want to know the status up to the last 10 days. ...
0
8445
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
8356
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
8781
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...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
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
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
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...
1
2771
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1776
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.