How can I find multiple special characters in batch? - batch-file

I'm trying to go through a .csv file I've copied in a .txt, and find any line that has any of these characters \ / : * ? " ' < >.
In this code I use find to output all line containing "/", but how can I look for every line with one of the special characters above?
#echo off
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
mkdir Output
copy "%%~I" Output\csvCopy.csv
)
for /f "tokens=2,* delims=;" %%a in (Output\csvCopy.csv) do ( echo %%b >> Output\debug.txt )
find /N "/" Output\debug.txt > Output\finalDebug.txt
start "" Output\finalDebug.txt
pause
#REM delete folder output
goto :EOF
: end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }

Related

Batch command to select multiple file and output it as single line

I tried to find a many way to finish this but still no hope ( tried with array etc ...)
Is there a way that I can select part of the file listed in the dir and output it as below
for example if I input 0-2, it output as
00000\.MTS+00001.MTS+00002.MTS
same , if I input 3-5,
00003\.MTS+00004.MTS+00005.MTS
EXAMPLE FOLDER LIST
2022-03-24 00:14 \<DIR\> .
2022-03-24 00:14 \<DIR\> ..
2022-03-23 15:47 5,025,792 00000.MTS
2022-03-23 15:47 4,958,208 00001.MTS
2022-03-23 15:47 3,938,304 00002.MTS
2022-03-23 15:47 9,185,280 00003.MTS
2022-03-23 15:48 9,179,136 00004.MTS
2022-03-23 15:48 3,028,992 00005.MTS
The reason I try to do this it is because I would like to join the MTS files without typing in one by one in the command. The original command is like
copy /b 00000.MTS+00001.MTS+00002.MTS+00003.MTS+00004.MTS+00005.MTS "C:\\Users\\Desktop\\1.MTS"
Hope I can use the batch command
1st : 0-2
copy /b 00000.MTS+00001.MTS+00002.MTS "C:\\Users\\Desktop\\1.MTS"
2nd : 3-5
copy /b 00003.MTS+00004.MTS+00005.MTS "C:\\Users\\Desktop\\2.MTS"
Is it possible to complete this in bat ?
I did try with the for loop to gen the file list,
setlocal enabledelayedexpansion
set /P "mts1=MTS SET 1 : "
for %%n in (%mts1%) do (
echo !FILE_LIST\[%%n\]!+
)
but seem it only show all and also every file uses a new line, cannot be use in copy /b
#ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory and destination directory are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files\t w o"
SET "destdir=%sourcedir%"
:: Do we have 2 arguments?
IF "%~2" equ "" ECHO need 2 arguments&GOTO :eof
:: calculate the destination filename
SET /a destfile=0
:destloop
SET /a destfile+=1
IF EXIST "%destdir%\%destfile%.MTS" GOTO destloop
:: change to source directory
PUSHD "%sourcedir%"
:: then build the list of files to concatenate
SET "sourcelist="
:again
FOR /f "tokens=1*delims=" %%b IN ('dir /b /a-d /on 0*.MTS ') DO (
SET "candidate="
SET /a candidate=1%%~nb 2>NUL
IF DEFINED candidate (
SET /a serial=candidate -100000
IF !serial! geq %1 IF !serial! leq %2 SET "sourcelist=!sourcelist!+%%~nxb"
IF !SERIAL! GEQ %2 IF "%3" NEQ "" SHIFT&SHIFT&GOTO AGAIN
)
)
IF DEFINED sourcelist COPY %sourcelist:~1% "%destdir%\%destfile%.MTS" >nul
:: back to original directory
POPD
GOTO :EOF
First step: get the destination filename by incrementing a counter and seeing whether that filename already exists.
Next: scan a basic directory list of the .MTS filenames that start 0. For each candidate found, set candidate to empty then attempt to user an arithmetic set (set /a) string 1 in front so that the number becomes, eg 100000. This is because numbers that start 0 are considered as octal by cmd. If the resultant string is not numeric, the set /a will fail, an error message will be produced (the 2>nul suppresses the error message) and candidate will remain set to empty, ie. undefined.
If candidate is defined, then subtract the 100000 that was added in, and check whether the result is greater than or equal to the first parameter AND less than or equal to the second parameter. If so, build sourcelist with the new name preceded by +.
Finally, do the copy using substringing to drop the leading + from sourcelist.
Run the batch with two parameters, the start and end numbers, eg. thisbatch 3 7
Amendment in response to comment:
Insert the label :again and add the extra line IF !serial! geq %2...
When the first range is ended, set serial to the current 3rd argument. If serial is now defined, shift out the first two arguments and start over, with sourcelist already part-built.
Note that this allows any pairs to be used, so thisbatch 12 15 3 6 is valid, as is thisbatch 12 14 3 7 6 11
--- Small revision
#ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory and destination directory are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files\t w o"
SET "destdir=%sourcedir%"
:: Do we have 2 arguments?
IF "%~2" equ "" ECHO need 2 arguments&GOTO :eof
:restart
:: calculate the destination filename
SET /a destfile=0
:destloop
SET /a destfile+=1
IF EXIST "%destdir%\%destfile%.MTS" GOTO destloop
:: change to source directory
PUSHD "%sourcedir%"
:: then build the list of files to concatenate
SET "sourcelist="
:again
IF /i "%1"=="E" GOTO docopy
FOR /f "tokens=1*delims=" %%b IN ('dir /b /a-d /on 0*.MTS ') DO (
SET "candidate="
SET /a candidate=1%%~nb 2>NUL
IF DEFINED candidate (
SET /a serial=candidate -100000
IF !serial! geq %1 IF !serial! leq %2 SET "sourcelist=!sourcelist!+%%~nxb"
IF !SERIAL! GEQ %2 IF "%3" NEQ "" SHIFT&SHIFT&GOTO AGAIN
)
)
:docopy
IF DEFINED sourcelist COPY %sourcelist:~1% "%destdir%\%destfile%.MTS" >nul
:: back to original directory
POPD
IF /i "%1"=="E" shift&GOTO restart
GOTO :EOF
This gives you the best of both worlds.
If you have a command line thisbatch 3 6 0 2 then it will generate 1 new file with 3+4+5+6+0+1+2.
If you have a command line thisbatch 3 6 0 2 E 12 15 0 2 E 1 4 then it will generate 3 new files with 3+4+5+6+0+1+2, 12+13+14+15+0+1+2 and 1+2+3+4.
The names for each number-pair are concatenated as before. If the next "start number" is E (either case) then the copy command is executed, the E is shifted out and the entire process restarted with arguments of whatever was beyond the E by returning to the label with the bizarre name :restart.
This can be used at a cmd prompt or in a batch-file script. The function builds an array of desired numbers. The desired numbers are expressed as a string similar to many applications specifying page numbers (ie: "1-3" or "3-5,7,10-12")
Place the Do-ConcatFiles.bat and Do-ConcatFiles.ps1 script in the same directory. If you are on a supported windows system, PowerShell is available.
=== Do-ConcatFiles.bat
#ECHO OFF
powershell -NoLogo -NoProfile -File "%~dpDo-ConcatFiles.ps1" -PagesList 1-3,12 -Path ".\pageslist.txt"
=== Do-ConcatFiles.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]$PagesList = '1-3,5,7-12'
,[Parameter(Mandatory=$true)]
[string]$Path = 'C:\src\t\pageslist\pageslist.txt'
)
function Get-PagesList([string]$PagesString) {
# Build an array of desired numbers.
$Pages = #()
$PagesString -replace '\s*' -split ',' |
ForEach-Object {
if ($_ -match '(\d*)\-(\d*)') {
for ([int]$i = [int]$Matches[1]; $i -le [int]$Matches[2]; $i++) { $Pages += $i }
} else { $Pages += $_ }
}
return $Pages
}
<# TEST FILE GENERATION
1..20 | ForEach-Object {
$FileName = ('{0:000000}' -f $_) + '.txt'
Set-Content -Path $FileName -Value $FileName -Encoding ascii
}
#>
Write-Verbose "Input PagesList = $PagesList"
Write-Verbose "Input result file is $Path"
$Pages = Get-PagesList($PagesList)
if ($Pages.Count -ne 0) {
if (Test-Path -Path $Path) { Remove-Item -Path $Path }
$Files = Get-ChildItem -Path '[0-9]*.txt'
$Pages |
ForEach-Object {
foreach ($File in $Files) {
if (($File -match '(\d*).txt') -and ([int]$Matches[1] -eq $_)) {
Write-Verbose "Appending file $File to $Path"
Get-Content -Path $File | Out-File -FilePath $Path -Append -Encoding ascii
}
}
}
}

Batch script calculate integer (add) from each row from multiple text files

I have multiple text files contains integer on each row. Can loop for /f calculate (add) from each row of each file sequentially?
Lets say the text files are like this:
File1.txt
123
213
321
File2.txt
111
222
333
File3.txt
333
222
111
Is it possible iterate over multiple files content and sum the like rows IE:
file1 row1 + file2 row1 + file3 row1
file1 row2 + file2 row2 + file3 row2
file1 row3 + file2 row3 + file3 row3
:: operation for 1st row of each file should be:
Set /A calc=123+111+333
echo !calc!
After googling around, I could not find any solution similar to my problem.
Appreciate if anyone can provide insight on this.
Thanks
you can use a single for loop over the output of findstr to build counts from each lines value.
#Echo off & CD /D "%~dp0"
cls
Setlocal
For /f "tokens=1 Delims==" %%g in ('set Line[ 2^> nul')Do Set "%%g=" 2> nul
For /f "tokens=2,3 delims=:" %%i in ('%Systemroot%\System32\Findstr.exe /n /r "^[0123456789]*$" "file*.txt"')Do (
Set /A "Line[%%i]+=%%j+0" 2> nul
)
Set Line[
Endlocal
You can use an array this way:
#echo off
setlocal EnableDelayedExpansion
for %%f in (file*.txt) do (
set "i=1"
for /F %%n in (%%f) do set /A "calc[!i!]+=%%n, i+=1"
)
set /A i-=1
for /L %%i in (1,1,%i%) do echo calc[%%i] = !calc[%%i]!
This batch-file that is run by cmd uses a PowerShell script. It creates a hash item for each line and accumulates the sum for each.
#powershell.exe -NoLogo -NoProfile -Command ^
"$h = #{};" ^
"Get-ChildItem -Filter 'filefile*.txt' |" ^
"ForEach-Object {" ^
"$LineNumber = 0;" ^
"Get-Content -Path $_.FullName |" ^
"ForEach-Object { $h[$LineNumber++] += [int]$_ }" ^
"};" ^
"0..($h.Count-1) | ForEach-Object { $h[$_] }"
This is a lot easier and clearer if written in a .ps1 file.
$h = #{}
Get-ChildItem -Filter 'filefile*.txt' |
ForEach-Object {
$LineNumber = 0
Get-Content -Path $_.FullName |
ForEach-Object { $h[$LineNumber++] += [int]$_ }
}
0..($h.Count-1) | ForEach-Object { $h[$_] }
You may see this get downvoted by someone who thinks PowerShell is not part of cmd. PowerShell is just as much a part of cmd as are find.exe, ipconfig.exe, and setx.exe. PowerShell is available on all supported Windows systems.
You can use findstr in a single for loop and set results sequentially per file:
#echo off & setlocal enabledelayedexpansion
for /f "tokens=1*delims=:" %%i in ('findstr /R "[0-9]" file*.txt') do (
set /a %%~ni+=1 & set /a _Result[!%%~ni!]+=%%j
)
set _Result
Each line per file's lines will be added together, result (based of your current examples:
For a drop single sum files on me approach:-
Summation.bat
#echo off & SETLOCAL ENABLEDELAYEDEXPANSION & Title Summation
for /f "tokens=1* delims=[]" %%A in ('find /n /v "%Title%" "%~1"') do (set "L%%A=%%B" & set "count=%%A")
set calc=0 & for /L %%i in (1,1,!count!) do (set /a calc = !calc! + !L%%i!)
echo/ & echo Line Count = !count! ^& Sum = !calc! & echo/ & pause
Command Line Usage >Summation File1.txt
NOTE as per comment by #T3RROR below
I misread your question as "Provide summation for a file at a time."
HOWEVER have kept it here for others wishing to sum each file.
Good batching, and may the cmd be with you :-)

How to write a Batch file to go to the directory mentioned in a variable inside for loop

How to write a Batch file to go to the directory mentioned in a variable inside for loop.
I have the below query which allows me to select a file through the file select dialog and I have placed the directory of the file in variable path1.
I need to go to this directory and then again create a folder there with the user input name.
I am writing the below code but echo !mypath! is showing the directory where the batch file is present.
<# : chooser.bat
:: launches a File
#echo off
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~dpI >> E:\Rajan\test.txt
set "path1=%%~dpI"
setlocal EnableDelayedExpansion
echo !path1! >> E:\Rajan\test2.txt
cd /D "!path1!"
set /p name =Enter your name
set mypath=%cd%
echo !mypath! >> E:\Rajan\test3.txt
md "%name%"
endlocal
)
goto :EOF
: #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.dmp)|*.dmp"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
I thought I put this on the previous question.
<# : chooser.bat
:: launches a File
#echo off
SET "THE_FILE="
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
SET "THE_FILE=%%~I"
)
CD /D "%THE_FILE%\..\"
set /p "name=Enter your name: "
set "mypath=%cd%"
echo %mypath% >>"E:\Rajan\test3.txt"
IF NOT EXIST ".\%name%" (md "%name%")
goto :EOF
: #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.dmp)|*.dmp"
$f.ShowHelp = $true
$f.Multiselect = $false
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
Here's my answer again, this time using powershell, instead of jscript, to invoke the dialog box.
#Echo Off
SetLocal EnableExtensions
For /F Delims^=^ EOL^= %%G In ('^"
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile ^
"(New-Object -COM 'Shell.Application').BrowseForFolder(0,'Select your directory.',1,0).Self.Path"
^"') Do MD "%%G\%UserName%"
As you can clearly see, the command using the output from the for-loop is exactly as I provided in my previous answer, and shows my comment, to be correct.

How To See Which One .bat file running on task scheduler

i have one task scheduler with 2 .bat file on action.
List .bat file on action tab
when task scheduler running how to i know which one .bat is running ?
this is xml file task scheduler:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2020-07-21T08:40:20.4842672</Date>
<Author>WIN-9DQ9EVI3R22\Administrator</Author>
<URI>\RESTORE</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT5M</Interval>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2020-07-21T00:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-316211975-241055689-3246940587-500</UserId>
<LogonType>Password</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"D:\Batch File\LS_RESTORE_221.bat"</Command>
</Exec>
<Exec>
<Command>"D:\Batch File\LS_RESTORE_MAINDB.bat"</Command>
</Exec>
</Actions>
</Task>
see at the xml file i have 2 .bat on action tag
this is .bat file script
sqlcmd -Q "exec SP_LS_RESTORE" -S WIN-9DQ9EVI3R22 -d dbSaaS_HOST_221 -o "D:\Batch File\LS_Restore_out_221.txt"
You can give a try for this batch file :
#echo off
Color 0B & Title Showing No Microsoft Scheduled Tasks List by Hackoo 2020
Set "TmpFile=%~n0_Abs_cmdline.txt"
Set "LogFile=%~n0_cmdline.txt
If Exist "%TmpFile%" Del "%TmpFile%"
If Exist "%LogFile%" Del "%LogFile%"
Set ProcessNames="cmd.exe" "wscript.exe" "cscript.exe"
SetLocal EnableDelayedExpansion
for %%A in (%ProcessNames%) Do (
Call :GetCommandLine %%A ProcessCmd
If defined ProcessCmd (
echo !ProcessCmd!>>"%TmpFile%"
)
)
If Exist "%TmpFile%" Call :Extract "%TmpFile%" "%LogFile%"
If Exist "%LogFile%" Start "" "%LogFile%"
echo(
echo( ****************************************************************************************************
echo( No Microsoft Scheduled Tasks List
echo( ****************************************************************************************************
Set "EXT=BAT"
#For /F "tokens=2,9 delims=," %%a in (
'SCHTASKS /Query /NH /FO CSV /V ^|find /I /V "Microsoft" ^|find /I /V "ADOBE" ^|findstr /I /C:"%EXT%"'
) do (
REM Set TaskName=%%~a
Set TaskPath=%%~b
REM Call :Trim_Dequote !TaskName! TaskName
Call :Trim_Dequote !TaskPath! TaskPath
REM echo "!TaskName!"
echo( "!TaskPath!"
)
Pause & exit
::-----------------------------------------------------------------------------------
:Trim_Dequote <Var> <NewVar>
Set "VbsFile=%Tmp%\%~n0.vbs"
(
echo Wscript.echo Trim_Dequote("%~1"^)
echo Function Trim_Dequote(S^)
echo If Left(S, 1^) = """" And Right(S, 1^) = """" Then Trim_Dequote = Trim(Mid(S, 2, Len(S^) - 2^)^) Else Trim_Dequote = Trim(S^)
echo End Function
)>"%VbsFile%"
for /f "delims=" %%a in ('Cscript //nologo "%VbsFile%"') do (
set "%2=%%a"
)
Del "%VbsFile%" /F >nul 2>&1
exit /b
::---------------------------------------------------------------------------------------------------------------
:GetCommandLine <ProcessName> <ProcessCmd>
Set "ProcessCmd="
for /f "tokens=2 delims==" %%P in (
'2^>nul wmic process where caption^="%~1" get commandline /format:list ^| findstr /I "%~1" ^| find /I /V "%~nx0"'
) do (
if not defined %2 Set "%2=%%P"
)
Exit /b
::---------------------------------------------------------------------------------------------------------------
:Extract <InputData> <OutPutData>
(
echo Data = WScript.StdIn.ReadAll
echo Data = Extract(Data,"(^?^!.*(\x22\w\W^)^).*(\.ps1^|\.vbs^|\.vbe^|\.js^|\.jse^|\.cmd^|\.bat^|\.wsf^|\.exe^)(^?^!.*(\x22\w\W^)^)"^)
echo WScript.StdOut.WriteLine Data
echo Function Extract(Data,Pattern^)
echo Dim oRE,oMatches,Match,Line
echo set oRE = New RegExp
echo oRE.IgnoreCase = True
echo oRE.Global = True
echo oRE.Pattern = Pattern
echo set oMatches = oRE.Execute(Data^)
echo If not isEmpty(oMatches^) then
echo For Each Match in oMatches
echo Line = Line ^& Trim(Match.Value^) ^& vbcrlf
echo Next
echo Extract = Line
echo End if
echo End Function
)>"%tmp%\%~n0.vbs"
cscript /nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::---------------------------------------------------------------------------------------------------------------
EDIT on 23/08/2020 #16:45 :
This is a Hybrid code Batch and Powershell that help us to show All No Microsoft Scheduled Tasks.
Show_No-Microsoft_Tasks.bat
<# : Batch portion
#rem # The previous line does nothing in Batch, but begins a multiline comment block
#rem # in PowerShell. This allows a single script to be executed by both interpreters.
#echo off
Title Get Schedule Tasks with a Hybrid code Batch and Powershell Script by Hackoo 2020
echo(
rem # This a Powershell command executes the hybrid portion at the bottom of this script
rem #for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
>"%~dpn0.txt" (
#for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0}|out-string)"') do echo %%I
)
REM TimeOut /T 3 /NoBreak>nul
If Exist "%~dpn0.txt" Start "" "%~dpn0.txt" & exit /b
rem # End multi-line PowerShell comment block. Begin PowerShell scripting.
: end Batch / begin PowerShell hybrid code #>
Function getTasks($path) {
$out = #()
# Get root tasks
$schedule.GetFolder($path).GetTasks(0) | % {
$xml = [xml]$_.xml
$out += New-Object psobject -Property #{
"Name" = $_.Name
"Path" = $_.Path
"LastRunTime" = $_.LastRunTime
"NextRunTime" = $_.NextRunTime
"Actions" = ($xml.Task.Actions.Exec | % { "$($_.Command) $($_.Arguments)" }) -join "`n"
}
}
# Get tasks from subfolders
$schedule.GetFolder($path).GetFolders(0) | % {
$out += getTasks($_.Path)
}
#Output
$out
}
$tasks = #()
$schedule = New-Object -ComObject "Schedule.Service"
$schedule.Connect()
# Start inventory
$tasks += getTasks("\")
# Close com
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($schedule) | Out-Null
Remove-Variable schedule
# To show All No Microsoft Scheduled Tasks
$tasks | ? { $_.Path -notmatch "Micro*" }
Read-Host 'Type any key to continue'
$tasks | ? { $_.Path -notmatch "Micro*" } | Out-GridView
Read-Host 'Type any key to continue'
<#
# Output all tasks
#$tasks | Out-GridView
#Read-Host 'Type any key to continue'
# To show only tasks with those extensions in their TaskPath
#$tasks | ? { $_.Actions -match "(\.vbs|\.vbe|\.cmd|\.bat|\.hta)" } | Out-GridView
#Read-Host 'Type any key to continue'
#>

Clean up a CSV file

I use a .bat file to move a CSV that is created every day. I now need to clean it up:
find and replace "-" to 0
find and replace empty cells with 0
remove all spaces
The CSV is only 20 lines.
Don't really know, what you need. Please explain more, if this doesn'w work for you:
for /f "delims=" %%a in (old.csv) do (
set "line=%%a"
setlocal enabledelayedexpansion
set "line=!line: =!"
set "line=!line:-=0!"
>> new.csv echo(!line!
endlocal
)
Batch files are not a good tool for this. You'd be far better off using PowerShell:
(Get-Content 'C:\path\to\in.csv') `
-replace ' ', '' `
-replace '-', '0' `
-replace '^,', '0,' `
-replace ',$', ',0' `
| % {
while ($_ -match ',,') { $_ = $_ -replace ',,', ',0,' }
$_
} | Out-File 'C:\path\to\out.csv'
or even VBScript:
Set fso = CreateObject("Scripting.FileSystemObject")
inFilename = "C:\path\to\in.csv"
outFilename = "C:\path\to\out.csv"
Set inFile = fso.OpenTextFile(inFilename)
Set outFile = fso.OpenTextFile(outFilename, 2, True)
outFile.WriteLine inFile.ReadLine 'write header
Do Until inFile.AtEndOfStream
line = inFile.ReadLine
line = Replace(line, " ", "")
line = Replace(line, "-", "0")
If Left(line, 1) = "," Then line = "0" & line
If Right(line, 1) = "," Then line = line & "0"
Do While InStr(line, ",,") > 0
line = Replace(line, ",,", ",0,")
Loop
outFile.WriteLine line
Loop
inFile.Close
outFile.Close
#ECHO OFF
SETLOCAL
(
FOR /f "delims=" %%i IN (yourfile.csv) DO (
SET "line=%%i"&CALL :process
)
)>newcsv.csv
GOTO :EOF
:process
SET line=%line: =%
SET line=%line:-=0%
SET line2=%line%
SET line=%line:,,=,0,%
IF NOT "%line%"=="%line2%" GOTO process
IF "%line:~0,1%"=="," SET line=0%line%
ECHO %line%
GOTO :EOF
Now the interweb fairies are finally back on board, here's my version...

Resources