tool or vbscript to delete first x lines from multiple files? - scripting

I've fiddled a bit with wingrep but doesn't seem to support this.
Has anyone had any luck with say deleting the first 7 lines of text from all .txt files in directory "C:\my_direc\"?
I'm using Win XP.

Here's a VBScript solution. Haven't tested it, but it should at least put you on the right track.
Dim FSO, txs, fld, fil, content, nLinesToSkip, i
Set FSO = CreateObject("Scripting.FileSystemObject")
nLinesToSkip = 7
fld = FSO.GetFolder("C:\test\")
For Each fil In fld
If Right(fil.Name, 3) = "txt" Then
Set txs = fil.OpenAsTextStream(1) ' 1 = for reading
For i = 1 To nLinesToSkip
txs.SkipLine
Next i
content = txs.ReadAll
txs.Close
Set txs = fil.OpenAsTextStream(2) ' 2 = for writing
txs.Write content
txs.Close
End If
Next fil

You can try Delete Lines tool

Related

execute CMD command via VBA -shell

Below is the example data availble in txt file
I want to extract the data in another txt file which Sr no is 1.
Please suggest me the VBA code which execute CMD command and bifurcate the data in another txt file.I have search the internet and got to know it is possible via use Shell(" "). help me to achieve my above object.
My txt file(i.e. file3) is available in Z:\ drive.
via below code i can open the cmd command window
Sub macro()
Call Shell("cmd.exe", vbNormalFocus)
End Sub
The Call Shell(,) command is what loads CMD.
If you want to load a file from the CMD, through VBA, you would use something such as:
Sub Open_CPT()
Dim Loc As String
Loc = "Z:/#CPT.bat"
Call Shell(Loc, 1)
End Sub
This will open the file or item at that location.
Depending how you want to bifurcate/split your data, you might want to use the native function of Excel/VBA to open the file and delimit by spaces/tabs/etc. You can then save as a .txt file, after modifications have been made how you want.
Thanks for your guidance as per the instructions of Dave I have developed the below code with the help of FileSystemObject
Please find the below solution.
Sub VBA()
Dim fr, t As String
Dim s As String
ReDim arr(500) As String
ReDim arri(500) As String
Dim i As Long
i = 0
ii = 0
Dim n As Integer
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fr = "z:\file3.txt"
Set oFS = fso.OpenTextFile(fr)
Do While Not oFS.AtEndOfStream
arr(i) = oFS.ReadLine
sls = InStr(1, arr(i), 1, vbTextCompare)
If sls >= 1 Then
arri(ii) = arr(i)
ii = ii + 1
End If
i = i + 1
Loop
oFS.Close
n = FreeFile()
s = arri(0)
For ix = LBound(arri) + 1 To UBound(arri)
s = s & vbCrLf & arri(ix)
Next
Open "z:\file2.txt" For Output As #n
Print #n, s
End Sub

VBA Read a texts files: permission denied

I have a folder contain texts files . The text is presented as below :
NAME Number Mail Date
xx 1 zz //
and I want to write a vba code that read all the text files and search for an information "NAME" to replace it with "name"and then save the modifications .
I did the code below , but I have an error 70 permission denied in Set f = FSO.OpenTextFile(Fichier, forWriting, True) ,
could you help me ?
Sub Sample()
dim fso=createobject("scripting.filesystemObject")
dim f
dim path as string
dim file_txt as string
path= "C:\Users\Folder\Fileshere\"
file_txt= Dir(path & "*.*")
Do While Len(file_txt) > 0
'Set objfile = FSO.CreateTextFile(path & file_txt)
Set f = FSO.OpenTextFile(file_txt, ForReading)
While Not f.AtEndOfStream
Namechange = f.ReadAll
Wend
Namechange = Replace(Namechange , "NAME", "name")
Set f = FSO.OpenTextFile(file_txt, forWriting, True)
f.Write Namechange
file_txt=dir()
loop
end sub
I'd rewrite using a bit more of the FileSystemObject functionality rather than using Dir() personally, but that's open to your own choice. The key issue I think you are having is that you have opened the file for reading and then immediately tried to open it for writing while the TextStream object is still in memory, and locking the file. This is why you are getting "Permission denied". To quote from a TechNet Article:
Opening Text Files
Working with text files is a three-step process.
Before you can do anything else, you must open the text file. This can
be done either by opening an existing file or by creating a new text
file. (When you create a new file, that file is automatically opened
and ready for use.) Either approach returns a reference to the
TextStream object. After you have a reference to the TextStream
object, you can either read from or write to the file. However, you
cannot simultaneously read from and write to the same file. In other
words, you cannot open a file, read the contents, and then write
additional data to the file, all in the same operation. Instead, you
must read the contents, close the file, and then reopen and write the
additional data. When you open an existing text file, the file can be
opened either for reading or for writing. When you create a new text
file, the file is open only for writing, if for no other reason than
that there is no content to read. Finally, you should always close a
text file. Although this is not required (the file will generally be
closed as soon as the script terminates), it is good programming
practice.
My code should work for your requirements. I've removed the While loop from the middle as if you are using ReadAll then you don't need to loop over the text.
Sub MySub()
Dim fso
Set fso = CreateObject("scripting.filesystemObject")
Dim file, folder
Dim path As String
Dim file_txt As String
path = "C:\users\folders\fileshere\"
Set folder = fso.GetFolder(path)
For Each file In folder.Files
Set file = fso.OpenTextFile(file.Path, 1)
Namechange = file.ReadAll
file.Close
Namechange = Replace(Namechange, "NAME", "name")
Set file = fso.OpenTextFile(file.Path, 2, True)
file.Write Namechange
file.Close
Next
End Sub
If you have any difficulties or would like further explanation of the above, let me know.
Some minor changes and it worked for me. Please change the path as per your own requirement in following code:
Sub change_txt()
Dim fso As Object
Set fso = CreateObject("scripting.filesystemObject")
Dim f
Dim path As String
Dim file_txt As String
path = "D:\Folder\Fileshare\"
file_txt = Dir(path & "*.*")
Do While Len(file_txt) > 0
'Set objfile = FSO.CreateTextFile(path & file_txt)
Set f = fso.opentextfile(path & file_txt, 1)
While Not f.AtEndOfStream
Namechange = f.ReadAll
Wend
Namechange = Replace(Namechange, "NAME", "name")
Set f = fso.opentextfile(path & file_txt, 2)
f.Write Namechange
file_txt = Dir()
Loop
End Sub

VBA open the folder before

I want to open the folder before the current Directory each time. I tried "..\" but it didn't work, can you help me with that N
ThecurrentDirectory= fso.GetParentFolderName(objFile)
Set myWorkBook = myxlApplication.Workbooks.Open( ThecurrentDirectory & "\..\CLIENTS.xlsx" )
If objFile is a file object then you can chain it's ParentFolder property together multiple times to get the disred result:
Dim fso, f
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set objFile = fso.GetFile("C:\Users\best buy\Downloads\stackoverfow\test.xlsm")
Output:
objFile.ParentFolder.ParentFolder = C:\Users\best buy\Downloads
Just pack the ThecurrentDirectory in another fso.GetParentFolderName.
ThecurrentDirectory= fso.GetParentFolderName(objFile)
Set myWorkBook = myxlApplication.Workbooks.Open( fso.GetParentFolderName(ThecurrentDirectory) & "\CLIENTS.xlsx" )

getting VBA to Append txt from bottom to top

I would like to append a text (.txt) file backwards is this possible?
By backwards I mean writing text from bottom to top rather then the standards top to bottom.
Why because the txt file I want to compile is read so that items at the top of the list are given priority to those at the bottom.
I can't think of any other way than to create a new file whenver you want to insert data at the top and then delete/rename the old one and rename the new file to the new one.
Not sure exactly your requirements BUT the easiest way in VBA is to
1. Add a reference to the Microsoft Scripting Runtime.
Public Sub Reverse()
Dim lReverseString As String
Dim lFSO As FileSystemObject
Set lFSO = New Scripting.FileSystemObject
With lFSO.OpenTextFile("SourceName", ForReading)
While Not .AtEndOfStream
' Note if you are looking to read a line at at a time use .ReadLine Instead of .Read
lReverseString = .Read & lReverseString
Wend
End With
' now you have a string in reverse
With lFSO.CreateTextFile("TargetName", True, False)
.Write lReverseString
.Close
End With
End Sub
This is a basic form which should get you going.
How about an array? It would not be suitable with a very large file:
Dim fs As Object
Dim ts As Object
Dim AllTextArray As Variant
''Late binding, no reference required
Set fs = CreateObject("Scripting.FileSystemObject")
''ForReading=1
Set ts = fs.OpenTextFile("c:\docs\BookX.csv", 1)
AllTextArray = Split(ts.ReadAll, vbCrLf)
For i = UBound(AllTextArray) To 0 Step -1
Debug.Print AllTextArray(i)
Next
If it's just writing each paragraph or sentence in the reverse order than it appears:
Sub Test()
Dim currentDocument As Document
Set currentDocument = ActiveDocument
Dim sourceDocument As Document
Set sourceDocument = Documents.Add("c:\words.txt")
Dim i As Long
For i = sourceDocument.Paragraphs.Count To 1 Step -1
currentDocument.Range.InsertAfter sourceDocument.Paragraphs(i).Range.Text
DoEvents
Next
sourceDocument.Close wdDoNotSaveChanges
End Sub

Permission Denied when running VBScript

I have a vbs script which captures file information and then exports it to a csv file. I need to run the script on main drives such as C:\, E:\, I:\ and more, but each time I run for the main directory I get "Permission Denied" when I try to run it for a subfolder example C:\Program Files it works fine. I have tested this on different desktop machines and servers with full admin accounts and still get it.
What could be the issue with this code. test.vbs
Option Explicit
Dim objFS, objFld
Dim objArgs
Dim strFolder, strDestFile, blnRecursiveSearch
Dim strLines()
Dim i
Dim strCsv
i = 0
' 'Get the commandline parameters
' Set objArgs = WScript.Arguments
' strFolder = objArgs(0)
' strDestFile = objArgs(1)
' blnRecursiveSearch = objArgs(2)
'###################################
'MAKE SURE THESE VALUES ARE CORRECT
'###################################
strFolder = "C:\"
strDestFile = "C:\Output.csv"
blnRecursiveSearch = True
'Create the FileSystemObject
Set objFS=CreateObject("Scripting.FileSystemObject")
'Get the directory you are working in
Set objFld = objFS.GetFolder(strFolder)
'Now get the file details
GetFileDetails objFld, blnRecursiveSearch
'Write the csv file
Set strCsv = objFS.CreateTextFile(strDestFile, True)
strCsv.Write Join(strLines, vbCrLf)
'Close and cleanup objects
strCsv.Close
Set strCsv = Nothing
Set objFld = Nothing
Set strFolder = Nothing
Set objArgs = Nothing
Private Sub GetFileDetails(fold, blnRecursive)
Dim fld, fil
dim strLine(5)
If blnRecursive Then
'Work through all the folders and subfolders
For Each fld In fold.SubFolders
GetFileDetails fld, True
Next
End If
'Now work on the files
For Each fil in fold.Files
strLine(0) = fil.Path
strLine(1) = fil.Type
strLine(2) = fil.Size
strLine(3) = fil.DateCreated
strLine(4) = fil.DateLastModified
strLine(5) = fil.DateLastAccessed
Redim Preserve strLines(i)
strLines(i) = Join(strLine, ",")
i = i + 1
Next
end sub
Please advise and modify code if you know where the issue is.
If it's a permissions problem I would strongly recommend Process Monitor from Sysinternals to diagnose it. You should be able to watch the cscript process (or whatever is executing your script) and find out what kind of permission problem you're having.