text file parser using file operators

srinivassurapareddi

New Member
Joined
Sep 23, 2015
Messages
1
Hi There! I wanted to parse a text file searching for text "$$$$$" and append some come content at the end og the line where the text is found.

example:
Code:
input file:
Hi there! you read this msg
$$$$$ 1234,2345

output file:
Hi there! you read this msg
$$$$$ 1234,2345,6479

Added 6479 (default content). i wanted to do the same for all files in the folder. but this is sample i wanted to do. I could able to read line by line.

#
Sub start()
Dim FP As String, nFile As String, textline As String, pos As Integer
Dim flag As Boolean
Dim files As Variant
flag = True
'Get the folder path in string
FP = Application.ActiveWorkbook.Path
FP = FP & "\"
files = Dir(FP & "*.txt", vbNormal)
'loop for all files
While flag = True
If files = "" Then GoTo 0
nFile = FP & files
Open nFile For Input As #1
'text parser
Do Until EOF(1)
Line Input #1, textline
pos = InStr(textline, "$$$$$")
If pos <> 0 Then
textline = textline & ",6479"
Print #1, textline


End If
Loop
Close #1




files = Dir
Wend


0: Exit Sub



End Sub
#

i can not read and write the same time. I do not know i to use append!

Please help me

Regards,
Srini
 

Some videos you may like

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.

pgc01

MrExcel MVP
Joined
Apr 25, 2006
Messages
19,778
Hi Srini
Welcome to the board

You can read the file into a string, process it and update the file


This is an example. I wrote some lines in a file and ran the code.

Remark: For my test I used notepad in windows that has as line delimiter carriage return line feed.
In other systems or programs the line delimiter may be other(the 3 usual cases are just line feed, just carriage return or, like in the case of notepad in windows, the sequence carriage return line feed)

See if this example helps:

Open notepad, write some lines, some of them including "$$$$$", save the file and run (ammend the file pathanme):

Code:
Sub AddText()
Dim sPathname As String, sText As String
Dim vText As Variant
Dim fn As Integer
Dim j As Long

sPathname = "c:\tmp\test.txt"
  
' read the file text into a string
fn = FreeFile
Open sPathname For Input As #fn
sText = Input$(LOF(fn), #fn)
Close #fn

' process the text
vText = Split(sText, vbNewLine)
For j = 0 To UBound(vText)
    If InStr(vText(j), "$$$$$") Then vText(j) = vText(j) & ",6479"
Next j
sText = Join(vText, vbNewLine)

' write the result text into the file
fn = FreeFile
Open sPathname For Output As #fn
Print #fn, sText
Close #fn

End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,099,805
Messages
5,470,888
Members
406,733
Latest member
darzu

This Week's Hot Topics

Top