473,668 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rename Textfile by String within textfile

1 New Member
Hi,

I have a folder with hundreds of text files. Each text file contains a row with a date. I want to rename the text file with the date contained in this text file. Example: Suppose I have 2 textfiles, then one text file would contain a row like this:

DATE 1 February 2008

and the other would contain a row like this:

DATE 2 February 2008

The rows are not necessarily at the same position (e.g. it's not always the third row) All text files have in common that the date line starts with "Date". Right now the textfiles are named by numbers. How can I rename each text file by the date given within this file? In the above example, I want textfile 1 to be "1February2 008" and textfile 2 "2February2 008"

Thank you very much for your help!
Alexandra
Feb 7 '08 #1
6 1739
debasisdas
8,127 Recognized Expert Expert
You can follow these steps.

1.Read the content of the file
2.Create a file by that name.
3.Copy the content to the new file.
4.Delte the old file.

You have to use FileSystemObjec t for the purpose.
Feb 7 '08 #2
jamesd0142
469 Contributor
I fancied giving this a go also:

Came up with this which works:

sure you can edit it to suit:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. Imports System.IO
  4. Public Class Form1
  5.  
  6.     Dim date1 As String
  7.     Dim j As String
  8.     Dim i As Integer
  9.     Dim pos As Integer
  10.  
  11.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  12.         DeleteAllSubFolders("c:\a")
  13.     End Sub
  14.  
  15.     Private Sub DeleteAllSubFolders(ByVal StartPath As String)
  16.         Dim myfolder As DirectoryInfo = New DirectoryInfo(StartPath)
  17.         Dim mySubfolders() As FileInfo = myfolder.GetFiles()
  18.         Dim strFiles() As FileInfo = myfolder.GetFiles()
  19.  
  20.         For Each myItem As FileInfo In strFiles
  21.             'myItem.Delete()
  22.             'open File
  23.             Dim a As String = StartPath & "\" & myItem.ToString
  24.  
  25.             'read File
  26.             Dim EntireLine1 As String
  27.             Dim oFile1 As System.IO.File
  28.             Dim oRead1 As System.IO.StreamReader
  29.             If System.IO.File.Exists(a) = True Then
  30.                 oRead1 = oFile1.OpenText(a)
  31.                 EntireLine1 = oRead1.ReadToEnd
  32.                 oRead1.Close() 'test line
  33.             End If
  34.             Dim b As String = "2008" 'vbCrLf
  35.             'find date
  36.             date1 = EntireLine1.Substring(EntireLine1.IndexOf("DATE"), EntireLine1.IndexOf(b)) ', EntireLine1.IndexOf("2008"))
  37.  
  38.             'function cuts of the end of the line where it finds a return character or line feed...
  39.             For i = 1 To Len(date1)
  40.                 j = Mid(date1, i, 1)
  41.                 If a = vbCr Or a = vbLf Then
  42.                     Exit For
  43.                 End If
  44.             Next
  45.             date1 = Mid(date1, 6, i - 7)
  46.  
  47.             'rename File
  48.             If System.IO.File.Exists(a) = True Then
  49.                 System.IO.File.Move(a, StartPath & "\" & RTrim(date1) & ".txt")
  50.             End If
  51.  
  52.         Next
  53.  
  54.     End Sub
  55. End Class
  56.  
Feb 7 '08 #3
WinblowsME
58 New Member
Backup before you do a test run.

Expand|Select|Wrap|Line Numbers
  1. ' VBA
  2.  
  3. Sub Test()
  4.    Dim source_path As String
  5.  
  6.    source_path = "C:\Documents and Settings\WinblowsME\Desktop\Temp"
  7.  
  8.    Call Rename_Files(source_path)
  9. End Sub
  10.  
  11. Private Sub Rename_Files(source_path As String)
  12.    Dim regex As Object, file_name As String, curr_date As String
  13.  
  14.    Set regex = CreateObject("VBScript.RegExp")
  15.  
  16.    regex.Pattern = "\\*$"
  17.    source_path = regex.Replace(source_path, "\")
  18.  
  19.    file_name = Dir(source_path & "*.txt")
  20.  
  21.    Do While file_name <> ""
  22.       curr_date = Get_Date(source_path & file_name)
  23.  
  24.       If curr_date <> "" Then
  25.          Debug.Print source_path & file_name & "->" & source_path & curr_date & ".txt"
  26.  
  27.          'Name source_path & file_name As source_path & curr_date & ".txt"
  28.       End If
  29.  
  30.       file_name = Dir
  31.    Loop
  32. End Sub
  33.  
  34. Private Function Get_Date(file_name As String) As String
  35.    Dim regex As Object, curr_line As String, curr_date As String
  36.  
  37.    Set regex = CreateObject("VBScript.RegExp")
  38.  
  39.    regex.Pattern = "^ *DATE *[0-9]{1,2} *.* *[0-9]{4}"
  40.    curr_line = ""
  41.    curr_date = ""
  42.  
  43.    Open file_name For Input As #1
  44.       Do While Not EOF(1)
  45.          Line Input #1, curr_line
  46.  
  47.          If regex.Test(curr_line) Then
  48.             curr_date = curr_line
  49.             curr_date = Replace(curr_line, "DATE ", "")
  50.             curr_date = Replace(curr_line, " ", "")
  51.             Exit Do
  52.          End If
  53.       Loop
  54.    Close #1
  55.  
  56.    Get_Date = curr_date
  57. End Function
Feb 7 '08 #4
Killer42
8,435 Recognized Expert Expert
You can follow these steps. ...
  • Far too wasteful to copy everything - just rename them. (What if the files are huge? What if you don't have enough space to copy?)
  • You do not have to use FSO, there are a number of methods which can be used.
Alexandra, I don't think you told us what version of VB you're using.

Winnie, pretty sure you've got a bug in lines 48-50.
Feb 8 '08 #5
Robbie
180 New Member
Winnie, pretty sure you've got a bug in lines 48-50.
Yes, curr_line on lines 49 and 50 should be curr_date (since curr_date became curr_line on line 48). Line 49 removes "DATE ", then line 50 removes any spaces, probably in case there was a space before "DATE " which he doesn't want to exist.

What sounds dodgy to me though is this removal of any and all spaces; what if there are meant to be spaces? If you want to remove only the space to the left of "DATE ", you could use Mid() to see if it's a space, and then combine 2 Mid()s to piece the first and second half of the line (of the text file) together, on either side of the space which you want to leave out.
Feb 8 '08 #6
WinblowsME
58 New Member
Sorry, lines 49 and 50 should be curr_date. It was a last second change that I've overlooked.
Feb 8 '08 #7

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

Similar topics

2
2575
by: BjoernJackschina | last post by:
Hello, I just look for a capability to sort several words in view of alphabet. An example: stop is 'opst' reach is 'aechr' This should read in a new file so that I can look for same letter orders. When I find the same orders it is an anagram. My problem is to sort and to select the textfile. I need dataset for dataset. What is the best way to realize that.
1
3127
by: Michael Schindler | last post by:
Ich habe es nun erreicht, ein textfile einzulesen das nun zeile für zeile im datagrid angezeigt wird. Nun wäre es toll wenn ich das textfile zum beispiel nach jedem blank in eine spalte zerstückeln könnte und meine frage hier wie geht sowas? Ich habe nun das ganze mit folgendem code im datagrid, nur zu welchem zeitpunkt zerstückle ich das und meine eigentliche frage wie kann ich das dann in die jeweiligen spalten stellen?
3
6057
by: Saradhi | last post by:
Hi All, Here I am facing a performance problem with the TreeView Node renaming. I am displaying a hierarchy Data in a treeview in my Windows C# Application. My tree view represents an hierarchical view of Parent Nodes and projects where in a projectnode can be added to any ParentNode and hence we may have a project node added to 100 Parent nodes. In this one, I have an operation of Renaming a Project Node. So whenever I am doing the...
2
2596
by: chris | last post by:
Hi there, I am reading in a textfile which looks like this (there is no new line after the last number) 03 98661881 0407 566453 The code to load the textfile looks like this:
7
2529
by: Peter Proost | last post by:
Hi, I'm creating an import module to read data from old textfiles, run some calculations on them and save them to sql server. I've figured out how to do a select on textfile using a schema.ini file (my textfile is delimeted by a | ) But I've got on problem remaining, below you can so two example rows out of the textfile: 560000||TS|alu dak|0000000067|P400|20|7101|401|0|0|0|0|||||N|J 560039||KM|"De Gaer":
2
1673
by: Rain | last post by:
I have a textfile with multiple line. How do i get (for example) the 1st line or the 3rd line then change the line to something i want in C#? How do i delete a line in C#... or backspace in a textfile? for example 1st line 2nd line 3rd line 4th Line I want to read the 2nd line and change the string 2nd line to string 4th
0
1214
by: lumo2000 | last post by:
hello ng! i wrote a little application in php which searches along a webpage for a latin animal name and returns me the "normal" name. so all i need to do now is: o - load a textfile and read the latin names from a textfile (one line is one name of the animal) o - make a systemcall and launch my application (which will automatically create an file and appends the new latin name and the normal translation.)
3
2898
by: Arn | last post by:
I just started to learn C++ and have some problem when I read a hole line from a textfile. I would be grateful if anyone can tell me what is wrong with my code. I'm using Borland Developer Studio 2006. //------------------------------------------------------------------------------ // getFile //------------------------------------------------------------------------------ // Read from a textfile // Input: nameList (string) , FILENAME...
1
2809
by: asedt | last post by:
With my Excel macro and two text files I want to create a new textfile containing the first textfile then text from the sheet and then the second textfile. My problem is that i don't know how to append the second textfile. Sub mysub() Dim TempString As String 'Open the first file Dim fileA As Integer
0
8462
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
8893
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
8799
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
8586
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,...
0
7401
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6209
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
4205
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
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2026
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.