bat adds line at specific line number - windows

I'm taking this approach to add a line SOME TEXT TO BE ADDED to the top of an existing file. Is there a way to specify the exact line number to add the new text. For example, before the last line (and add a line break) or after the 3rd line (and add a line break)
copy original.txt temp.txt
echo.SOME TEXT TO BE ADDED>original.txt
type temp.txt >>original.txt
del temp.txt

Vbscript
strLineNum = WScript.Arguments(0)
strAddText= WScript.Arguments(1)
strFileName = WScript.Arguments(2)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
Do Until objFile.AtEndOfStream
linenum=objFile.Line
strLine = objFile.ReadLine
If linenum = CInt(strLineNum) Then
WScript.Echo strAddText
End If
WScript.Echo strLine
Loop
objFile.Close
Usage:
C:\test> cscript //nologo myscript.vbs 2 "text to insert" file >temp
C:\test> ren temp file

Related

Issue with batch script with vbscript command in the batch file

I am new to batch scripting and vbscript. What I want to do is convert .xlsx Excel files into .csv Excel files, in multiple directories (Recursively). For example:
Main directory
subdirectory1
file1.xlsx
file2.xlsx
subdirectory2
file3.xlsx
file4.xlsx
I have made this batch script:
FOR /r %%a in (*.xlsx) do (
SET filename=%%a
ExceltoCSV.vbs %filename% *.csv
)
Inside the for loop is the ExceltoCSV.vbs. I got this code from this thread Convert XLS to CSV on command line, and I have tried the top 2 answers already (Both don't require downloading anything).
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
The error is saying that the ExceltoCSV.vbs file cannot be accessed. However, I believe the batch script is working, for example it would say:
SET filename=C:\folder\subfolder\test1.xlsx
then it calls:
ExceltoCSV.vbs C:\folder\subfolder\test1.xlsx *.csv
I am not sure what the problem is and I am currently very confused.
The VBS needs to be in the same directory as the BAT file.
The issue is that variable expansion rules in a FOR loop mean that filename wont be set to the current file variables value; just use %%a instead:
FOR /r %%a in (*.xlsx) do (
ExceltoCSV.vbs "%%a" "%%~dpna.csv"
)
You are passing the string "*.CSV" to the script which wont work, %%~dpna.csv takes the file name in %%a and changes the extension to .CSV.
The quotes are there to allow for spaces in paths.
You're using VBScript to convert. Why not just use it to iterate your folders as well? Then you don't have to worry about calling a VBS from a BAT and passing the proper args.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oExcel = CreateObject("Excel.Application")
DoFolder "c:\mainfolder"
oExcel.Quit
Sub DoFolder(strFolder)
' Recursively process each subfolder...
For Each objSubFolder In objFSO.GetFolder(strFolder).SubFolders
DoFolder objSubFolder.Path
Next
' Convert any XLSX files...
For Each objFile In objFSO.GetFolder(strFolder).Files
If StrComp(objFSO.GetExtensionName(objFile.Name), "xlsx", vbTextCompare) = 0 Then
strNewName = Left(objFile.Path, Len(objFile.Path) - 4) & "csv"
' Convert...
Set oBook = oExcel.Workbooks.Open(objFile.Path)
oBook.SaveAs strNewName, 6
oBook.Close False
End If
Next
End Sub

Text encoding on WScript arguments

I'm trying to generate mail configurations and personalized signatures through a batch file that reads a list of users, a template, and creates a personalized output. That's done and works:
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS
GOTO begin
:writesignature
cscript //NoLogo replacetext.vbs "[NAME]" %1 signature.html stdout | cscript //NoLogo replacetext.vbs "[JOB]" %3 stdin stdout | cscript //NoLogo replacetext.vbs "[EMAIL]" %2 stdin signature-%4.html
GOTO :end
:begin
FOR /F "tokens=1,2,3,4 delims=;" %%A IN ('TYPE people.lst') DO CALL :writesignature "%%A" "%%B" "%%C" %%D
:end
To do the text replacing, I created replacetext.vbs, that allows me to replace a string for oter, and can be piped if stdin and stdout are indicated as the source and target files:
CONST ForReading = 1
CONST ForWritting = 2
CONST ForAppending = 8
CONST OpenAsASCII = false
CONST OpenAsUnicode = true
CONST OpenAsDefault = -2
Const OverwriteIfExist = true
Const FailIfExist = false
Const CreateIfNotExist = true
Const FailIfNotExist = false
SET objFSO = CreateObject("Scripting.FileSystemObject")
SET objFILEINPUT = Wscript.StdIn
SET objFILEOUTPUT = Wscript.StdOut
IF (Wscript.Arguments.Count < 2) OR (Wscript.Arguments.Count > 4) THEN
Wscript.Echo "Not enought arguments"
Wscript.Echo "replacetext ""<original>"" ""<replacement>"" "
Wscript.Quit(1 MOD 255)
END IF
IF Wscript.Arguments.Count > 2 THEN
IF Wscript.Arguments(2) = "stdin" THEN
' Wscript.Echo "Input: StdIn"
ELSE
' Wscript.Echo "Input: " + Wscript.Arguments(2)
SET objFILEINPUT = objFSO.OpenTextFile(Wscript.Arguments(2), ForReading, OpenAsASCII)
END IF
IF Wscript.Arguments.Count = 4 THEN
IF Wscript.Arguments(3) = "stdout" THEN
' Wscript.Echo "Output: StdOut"
ELSE
' Wscript.Echo "Output: " + Wscript.Arguments(3)
IF objFSO.FileExists(Wscript.Arguments(3)) THEN
SET objFILEOUTPUT = objFSO.OpenTextFile(Wscript.Arguments(3), ForWritting, CreateIfNotExist, OpenAsASCII)
ELSE
SET objFILEOUTPUT = objFSO.CreateTextFile(Wscript.Arguments(3), OverwriteIfExist, OpenAsASCII)
END IF
END IF
END IF
END IF
strText = objFILEINPUT.ReadAll()
strNewText = Replace(strText, Wscript.Arguments(0), Wscript.Arguments(1))
objFILEOUTPUT.Write(strNewText)
objFILEOUTPUT.Close
objFILEINPUT.Close
Wscript.Quit(0 MOD 255)
The problem is that when I put non-ASCII characters in ANSI/Windows-1250 in the people.lst (Comunicación), while it works and reads them in console, showing them (not converting them) as OEM characters (Comunicaci¾n) when I write the output files, somehow it does convert them transparently, so the output file in Windows shows Comunicaci¾n instead of Comunicación.
After much debugging, I've localized the problem in ONLY the arguments (no automatic conversion on the template file).
How can I disable said transparent conversion, or convert back the input from ANSI to OEM so the conversion works as intended?
The problem is that the cmd.exe works with different code page than cscript.exe/wscript.exe. I have similiar problem in Poland, where cmd.exe works with codepage 852 (I believe this is for compatibility with older MS-DOS programs) and wscript.exe works in Windows' native codepage 1250.
To solve the problem, put the following line on the beginning of the batch file:
mode con cp select=1250

Windows BAT : test if a specific file is empty

I would like to check if a specific file is empty in a windows .bat file. Here is my non working script :
set dir="C:\test"
set file="%dir%\fff.txt"
cd %dir%
if %file%%~zi == 0 exit
ftp -s:"%dir%\ftp.action"
exit
Could you help me debug this please ?
Or try it with
#echo off
set "dir=C:\temp"
set "file=%dir%\a.txt"
call :CheckEmpty "%file%"
goto :eof
:CheckEmpty
if %~z1 == 0 exit
ftp -s:"%dir%\ftp.action"
goto :eof
The main difference is that I use a function call and use the %~z1, as the modifiers only works for paramters like %1, %2..%9 or for-loop parameters like %%a ...
batch solution using file compare:
type nul > blank
fc myfile blank > nul
if errorlevel 1 echo myfile is not empty
Try this:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\boot.ini", ForReading)
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close

Fetching the matched string from the text using findstr

I have a text in some file like
<Variable name="URL" value="http://url:port"/>
I want the url in the value tag( http://url:port ).
The command and regex I'm using are
FindStr /R /C:"\"URL\" *value=*\"*\"" <filename>
The above regex matches the line in the file but fails to extract that url string
any suggestion?
findstr will not capture any values for you. If you can download tools, you can try gawk for windows
C:\test>gawk "/value/{ gsub(/.*value=\042|\042.*/,\"\");print }" file
http://url:port
If not, you can use vbscript
strFile= WScript.Arguments(0)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set d = CreateObject("Scripting.Dictionary")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine=objFile.ReadLine
If InStr(strLine,"value=") > 0 Then
s=Split(strLine,"value=")
s1=Replace(s(1),"/>","")
WScript.Echo s1
End If
Loop
usage:
C:\test>cscript //nologo test.vbs file
"http://url:port"

bat read a file line by line

In my bat script, is it possible to access a txt file and read it line by line. The idea I'm having is to check if the line starts with an identifier word (in my case 1 or 2 stars * or **) but to do this I need to read the file line by line.
you can use vbscript
strToFind= WScript.Arguments(0)
strToFind = Replace(strToFind,"*","\*")
strFileName = WScript.Arguments(1)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
Set objRE = New RegExp
objRE.IgnoreCase = False
objRE.Pattern = "^"&strToFind&".*"
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
Set Matches = objRE.Execute(strLine)
'WScript.Echo Matches.Count
For Each Match in Matches ' Iterate Matches collection.
WScript.Echo Match.Value
Next
Loop
objFile.Close
Usage:
C:\test>cscript //nologo myscript.vbs "**" file
Here's what I found: http://www.computing.net/howtos/show/batch-file-tip-reading-writing-every-line-of-a-file/61.html
Hope that helps..
CODE:
#echo off
for /f "delims=] tokens=1*" %%a in ('find /v /n "" ^<%1') do (
echo.%%b
)

Resources