I'm looking for a VBscript which scan a folder for files and remove number from filenames. for example if we have a file named "target1990.txt" then It should be "target.txt"
Can anyone help please?
Use a RegExp that looks repeatedly/globally for a sequence of digits (\d+) and replace all matches with "" (nix):
>> set r = New RegExp
>> r.Global = True
>> r.Pattern = "\d+"
>> s = "target1990.txt"
>> WScript.Echo s, r.Replace(s, "")
>>
target1990.txt target.txt
further sample (same regexp):
>> s = "t1ar33get19s90.txt"
>> WScript.Echo s, r.Replace(s, "")
>>
t1ar33get19s90.txt targets.txt
Related
Can someone tell me what
if(!IsNumeric(aNumber))
{
do something
}
is in valid VBScript? I've tried
!IsNumeric(aNumber)
already.
The logical negation operator is called Not in VBScript:
>> b = 1 = 1
>> WScript.Echo TypeName(b), CStr(b), CStr(Not b)
>>
Boolean True False
>>
2nd sample:
>> For Each e In Split("1 a 2")
>> If Not IsNumeric(e) Then
>> WScript.Echo e, "not a number"
>> Else
>> WScript.Echo e, "a numerical string"
>> End If
>> Next
>>
1 a numerical string
a not a number
2 a numerical string
>>
I am trying to get the last modified date of a log file on a remote Windows server 2008/2012 with a batch script.
I am connecting to the machine using "net use", and able to see if the file exists.
net use \\X.X.X.X /user:%USERNAME% %PASSWORD%
if exist "\\X.X.X.X\\C$\\Temp\\LogFiles\\abcd" (
echo ABCD file exists on the server
) else (
echo ABCD file does NOT exist on the server
)
Also, I am able to get the last updated time of a local file using forfiles:
for /f "delims=" %%i in ('"forfiles /m MyLocalAbcd /c "cmd /c echo #file was last modified at #ftime" "') do set modif_time=%%i
echo %modif_time%
However, I am not able to get the modified time of the remote file. I tried to provide the complete path - forfiles /M "\X.X.X.X\C$\Temp\LogFiles\abcd" - or even providing the path to the option P of forfiles, but it is not finding the file.
Is there an easy way to get the modified date/time of the remote file?
Also, I am wondering if there is a way to tail the last n lines of the same file with a Windows built-in command.
Any help is appreciated!
Thanks!
Try a dir.
Or use a for loop differently.
for %%A in (\\server\C$\Temp\LogFiles\abcd) do echo %%~tA
A working example if pasted into a command prompt.
for %A in (\\127.0.0.1\C$\windows\win.ini) do echo %~tA
To the other question you sneeked in
more +50 skips first 50 lines.
This VBScript does what you want.
Set Arg = WScript.Arguments
Set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
To use
Filter reads and writes standard in and standard out only. These are only available in a command prompt.
filter <inputfile >outputfile
filter <inputfile | other_command
other_command | filter >outputfile
other_command | filter | other_command
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
filter cut t i 5 < "%systemroot%\win.ini"
I found this code:
Option Explicit ' .. Just coz.
Const forReading = 1 ' Set our constants for later.
Const forWriting = 2 ' ....
Dim inputFile, outputFile, fso, fileList, logFile, fileSpec ' Dimension our variables
inputFile = "filelist.txt" ' Our input file
outputFile = "missing.txt" ' Our output file
Set fso = CreateObject("Scripting.FileSystemObject") ' Set up fso
Set fileList = fso.OpenTextFile(inputFile, forReading) ' Open our input file for reading
If Not (fso.FileExists(outputFile)) Then fso.CreateTextFile(outputfile) ' Create output file if it doesn't exist
Set logFile = fso.OpenTextFile(outputFile, forWriting) ' Open up our output file for writing later
Do while not fileList.AtEndOfStream ' While we have lines to process do this loop
fileSpec = fileList.ReadLine() ' Read in line of text as variable fileSpec
If Not (fso.FileExists(fileSpec)) Then ' If it doesnt exist ....
logFile.writeline (fileSpec) ' ....Write it out to the output file
End If
Loop
fileList.close ' Clean up
logFile.close
Here is explanation of that code.
I need one more thing. I need move extra files from default directory (they are not write in filelist.txt) into the new directory. I need in default directory only files who are write in filelist.txt. I don't fully understand that code. I was try remake that code but each time failed.
Set problems (union, difference, ...) can be solved with a Dictionary in VBScript.
You have two sets of file names, one from your source file (SetF), one from the files in your default directory (SetD). In your existing loop over SetF, store the the names in a dictionary (DicF). Then add a loop over SetD (DefFolder.Files) and move the files that don't exist in DicF - as in:
>> SetF = Split("A D F G")
>> SetD = Split("B D G H")
>> Set DicF = CreateObject("Scripting.Dictionary")
>> For Each f in SetF
>> DicF(f) = 0
>> Next
>> For Each f In SetD
>> If Not DicF.Exists(f) Then
>> WScript.Echo f
>> End If
>> Next
>>
B
H
(cf. Compare arrays)
I'm trying this code:
filename = "test.txt"
listFile = fso.OpenTextFile(filename).ReadAll
listLines = Split(listFile, vbCrLf)
For Each line In listLines
WScript.Echo line
'My Stuff
Next
Or this other:
filename = "test.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename, ForReading)
Do Until f.AtEndOfStream
myLine = f.ReadLine
WScript.Echo myLine
'My Stuff
Loop
Why in both cases it echoes all lines at once, and of course I'm unable to work line by line? Any idea?
Your file has funny EndOfLine markers. Let's assume the lines are terminated by vbLf:
>> fn = "lf.txt"
>> goFS.CreateTextFile(fn).Write Replace("a b c ", " ", vbLf)
>> set ts = goFS.OpenTextFile(fn)
>> do until ts.AtEndOfStream
>> WScript.Echo ts.ReadLine
>> loop
>>
a
b
c
As you can see, .ReadLine can cope with vbLf (unix). Your Split() on .ReadAll(), however, will fail:
>> t = goFS.OpenTextFile(fn).ReadAll()
>> a = Split(t, vbCrLf)
>> WScript.Echo UBound(a)
>> WScript.Echo a(0)
>>
0
a
b
c
t does not contain a single vbCrLf, so Split() returns an array with UBound() == 0, containing t as its single element. .Echoing that will at least look like 3 (4) lines. You could Split() on vbLf, if you really need an array of lines.
But if your files contains vbLf endings, then the .ReadLine loop should work fine.
.ReadLine() can't cope with vbCr (mac):
>> fn = "cr.txt"
>> goFS.CreateTextFile(fn).Write Replace("a b c ", " ", vbCr)
>>
>> set ts = goFS.OpenTextFile(fn)
>> do until ts.AtEndOfStream
>> WScript.Echo ts.ReadLine
>> loop
>>
c
The b+cr 'overwrites' the a+cr and is then 'overwritten' by c+cr. The .ReadAll() approach will fail too, unless you use vbCr as separator.
But if your files contains vbCr endings, then none of your snippets can "echoe(s) all lines at once".
Does your file come from outer space?
Update wrt comment:
You can't read UTF-8 using the Filesystemobject. Either convert the file to UTF-16 and use the Unicode option of the format parameter when .OpenTextFile it, or work with an ADODB Stream.
It still would be interesting to know what EOL marker is used.
Your code seems to be working fine. I changed it slightly to show that the lines are, in fact, read line-by-line:
Set fso=CreateObject("Scripting.FileSystemObject")
filename = "test.txt"
listFile = fso.OpenTextFile(filename).ReadAll
listLines = Split(listFile, vbCrLf)
i = 0
For Each line In listLines
WScript.Echo CStr(i) + " : " + line
i = i + 1
'My Stuff
Next
I assume fso is set in your script somewhere, but I added that extra line just for completeness.
You should verify that your input file does, indeed, have multiple lines separated by vbCrLf. The counter i helps in debugging each line as it shows the line index during reading the lines.
I've been searching online. Is there a way to cut off the space and the rest of the filename but leave the extension with VBScript.
Say I have a filename like this:
filename this is a file.txt
Could VBScript cut off the space and everything afterwards but leave the extension like this:
filename.txt
Sure, you can do some surgery with the string functions available in vbscript.
dim s
dim s2
s = "filename this is a file.txt"
s2 = Left(s, Instr(s, " ")-1) & Right(s, Len(s) - InstrRev(s, ".") + 1)
msgbox s2
There are several ways to achieve what you want:
Using a regular expression:
Set fso = CreateObject("Scripting.FileSystemObject")
Set re = New RegExp
re.Pattern = "^(\S*).*(\..*?)$"
Set f = fso.GetFile("filename this is a file.txt")
f.Name = re.Replace(f.Name, "$1$2")
Using Split:
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("filename this is a file.txt")
f.Name = Split(fso.GetBaseName(f))(0) & "." & fso.GetExtensionName(f)
Using string functions: see answer provided by KekuSemau.
Use a RegExp to cut the first 'word' and the extension from your input:
>> Set r = New RegExp
>> r.Pattern = "^(\w+)(.*)(\..*)$"
>> For Each s In Array("filename this is a file.txt", "a.txt", "1a nix ...txt")
>> WScript.Echo s, """" & r.Replace(s, "$1$3") & """"
>> Next
>>
filename this is a file.txt "filename.txt"
a.txt "a.txt"
1a nix ...txt "1a.txt"
If you insist on staying with String ops, use Mid() instead of Right():
>> s = "filename this is a file.txt"
>> a = Left(s, InStr(s, " ") - 1)
>> b = Mid(s, InStrRev(s, "."))
>> WScript.Echo a, b, a & b
>>
filename .txt filename.txt