Bat file replace character - batch-file

I use bat script to backup MySQl database
SET SOURCEDIR="C:\Program Files\MariaDB\data\"
set now=%DATE:~-4%-%DATE:~3,2%-%DATE:~0,2%
for /d %%i in (%SOURCEDIR%\*) do (
if not "%%~ni"=="temp" "C:\Program Files\MariaDB\bin\mysqldump.exe" -uroot -h127.0.0.1 -c -e -q --single-transaction=TRUE %%~ni | "c:\Program Files\7-Zip\7z.exe" a -si"%%~ni_%now%.sql" "D:\backup\SQL\%now%\%%~ni.sql.7z"
)
exit
But if database have dot in name, for exapmle data.2023, then MariDB create folder data#002e2023
So SQL dump is empty.
How can I replace #002e to . in this script here *single-transaction=TRUE %%~ni | *?
%%~ni:#002e=!.!% is not working

Based upon your attempt, %%~ni:#002e=!.!%, I'd assume you need to create a variable, and delay variable expansion to use it.
Example:
#Set "SOURCEDIR=%ProgramFiles%\MariaDB\data"
#Set "now=%DATE%"
#Set "now=%now:~-4%-%now:~-7,2%-%now:~-10,2%"
#For /D %%G In ("%SOURCEDIR%\*") Do #If /I Not "%%~nxG" == "temp" (
Set "dirname=%%~nxG"
SetLocal EnableDelayedExpansion
"%ProgramFiles%\MariaDB\bin\mysqldump.exe" -uroot -h127.0.0.1 -c -e -q --single-transaction=TRUE !dirname:#002e=.!^
| "%ProgramFiles%\7-Zip\7z.exe" a -si"%%~nxG_%now%.sql" "D:\backup\SQL\%now%\%%~nxG.sql.7z"
EndLocal)

Related

run batch code directly from variable instead of script file

I have code similar to the following running on a few of my windows machines:
mybatch.bat
::set destdir=C:\SServer\var\db\hist\log-entry
set fileage=-7
set destdir="C:\SServer\var\db\hist\audit-log - Copy"
set recordsdir=C:\housekeeping\LOGS
set info_tempfile=%recordsdir%\cleanup.info
set status_tempfile=%recordsdir%\cleanup.status
set count_tempfile=%recordsdir%\cleanup.count
::set filepattern=log_exception-
set filepattern=AuditLog-
::set filepattern=temip
if not exist %recordsdir% (mkdir %recordsdir%)
if not exist %recordsdir% (
echo %DATE% %TIME% ERROR: Unable to create records directory [ %recordsdir% ] 1>> %status_tempfile%
)
forfiles -p %destdir% -s -m *%filepattern%* /D %fileage% /C "cmd /c echo /q #path" 2> %info_tempfile% 1> %count_tempfile%
I'm new to batch script so please forgive any abomination you may spot in the above code. What i'm trying to do here is identify how I can go about running code stored in a variable.
For instance, in powershell, you can run any piece of powershell code if you store it in a script block and pass it to the iex or invoke-expression command.
$scriptBlock = {
$welcomeMsg = "Hello, World!"
$welcomeMsg
}
iex "$scriptBlock"
I'm wondering if the same exist for batch?
How do I store the above batch code (mybatch.bat) in a variable and then pass it to say cmd.exe and have it execute as though it were in a file?

Conditional concatenation in batch

I am trying to append an underscore to strings when they are not blank. This is for a backup program, where the name of the folder is [prefix]_[date]_[time]_[suffix], except the first and last underscores are supposed to only be added when the [prefix] or [suffix] are not empty.
I've attempted to concatenate with set PRX=%PRX% and _ as I read on some forum, although the and wasn't recognized (it just outputted "backup and _"). I also tried jumping around the files with "goto", but to no avail. I think it's with the concatenation.
#echo off
set /p DRV=Enter drive/directory to back up (e.g. %userprofile% or C:):
set /p DRU=Enter directory to save to (e.g. C:\backup or F:):
set /p PRX=Enter the prefix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]:
set /p SFX=Enter the suffix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]:
if %PRX% NEQ "" (set PRX=%PRX%_)
if %SFX% NEQ "" (set SFX=_%SFX%)
set /p CONT=%CD%, Are you sure you want to continue (Y/N)?
if /i "%CONT%" EQU "N" goto :cancel
cls
echo Initialising...
%DRV:~0,1%:
cd\
set DAT=%date:~6,4%-%date:~3,2%-%date:~0,2%
set TIM=%time:~0,2%-%time:~3,2%-%time:~6,2%
mkdir "%DRU%\%PRX%%DAT%_%TIM%%SFX%"
echo Cloning Files...
echo.
xcopy "%DRV%\*" "%DRU%\%PRX%%DAT%_%TIM%%SFX%" /s
I inputted
Enter drive/directory to back up (e.g. %userprofile% or C:): %userprofile%\downloads
Enter directory to save to (e.g. C:\backup or F:): %userprofile%\backup
Enter the prefix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]: (that is empty)
Enter the suffix for the directory. Directory will be saved as [prefix]_[date]_[time]_[suffix]: aa
the outputted folder was named "_2019-09-10_17-08-35_aa" as opposed to "2019-09-10_17-08-35_aa", not what I was expecting.
I appreciate any reply, thank you for your time.
String comparison is very explicit.
IF "%PRX%" NEQ "" (SET "PRX=%PRX%_")
IF "%SFX%" NEQ "" (SET "SFX=_%SFX%")
It is easy to get correctly formatted data and time values regardless of region settings.
FOR /F %%A IN ('powershell -NoLogo -NoProfile -Command "Get-Date -Format 'yyyy-MM-dd'"') DO (
SET "DAT=%%A"
)
FOR /F %%A IN ('powershell -NoLogo -NoProfile -Command "Get-Date -Format 'HH-mm-ss'"') DO (
SET "TIM=%%A"
)

Saving cURL and jq output to a variable in batch script

I use this command in order to retrieve a result of a build in Jenkins:
curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result"
Based on that result I need to decide an action to be performed using a batch command,
How do I save the output of the command as a variable?
You should be able to use a For /F command in a batch file to return the output of a command to a variable:
For /F "Delims=" %%A In ('"curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result""') Do Set "test=%%~A"
If /I "%test%"=="failed" ...DoSomething
If /I "%test%"=="success" ...DoSomethingElse
If /I "%test%"=="unstable" ...DoAnotherThing
However there may be no need to set a variable at all, because you can work with the returned metavariable directly:
For /F "Delims=" %%A In ('
"curl -s http://<jenkins_url>/job/<job_name>/lastCompletedBuild/api/json | jq ."result""
') Do (
If /I "%%~A"=="failed" ...DoSomething
If /I "%%~A"=="success" ...DoSomethingElse
If /I "%%~A"=="unstable" ...DoAnotherThing
)

Append to a filename last modified date and time with a batch file

I am trying to copy all *.csv files from a folder to another folder, but while copying I need to add modified date and time of file to filename. For example, if filename is Test.csv and it was modified on 11/21/2018 15:01:10 output should be Test11-21-201815_01-10.csv. I found a script to add current timestamp to it, but I need to add modified date of file. You can see it below:
#echo off
set Source=C:\csvtest
set Target=C:\csvtest\csvtest\Archive
FOR /f "tokens=1-8 delims=/.:- " %%A in ("%date%%time%") DO (
SET Month=%%B
SET Day=%%C
SET Year=%%D
SET Hours=%%E
SET Minutes=%%F
SET Seconds=%%G
SET All=%%B-%%C-%%D_%%E-%%F-%%G
)
FOR %%i IN ("%Source%\*.csv") DO (
COPY "%%i" "%Target%\%%~Ni %All%.csv")
Thanks in advance for your help.
There are some examples here on SO for appending a date,
but I'd use PowerShell as a tool to accomplish this (wrapped in batch).
:: Q:\Test\2018\11\23\SO_53450598.cmd
#echo off
set "Source=C:\test"
set "Target=C:\test\Archive"
PowerShell -Nop -C "Get-ChildItem '%Source%\*.csv'|Copy-Item -Destination {'%Target%\{0} {1:MM-dd-yyyy_HH-mm-ss}.csv' -f $_.BaseName,$_.LastWriteTime} -WhatIf"
If the output looks OK, remove the -WhatIf at the end.
Here is a slightly faster way in batch file that uses delayedexpansion:
#echo off
setlocal enabledelayedexpansion
for /f "tokens=1-2" %%a IN ('forfiles /M file.ext /C "cmd /C echo #fdate #ftime"') do (
set line1=%%a
set line2=%%b
set line1r=!line1:/=-!
set line2r=!line2::=-!
rename "file.ext" "file!line1r!!line2r!.ext"
)
rem NOTE: Date format is DD-MM-YYYY. Time format is HH-MM-SS.
forfiles /M file.ext /C "cmd /C echo #fdate #ftime" runs the command (/C) for the file specified in /M option (file.ext).
"cmd /C echo #fdate #ftime" opens a new cmd and carry out the command specified by string and then terminates it.
#fdate is the last modified date of the file and #ftime is the last modified time of the file.
We set variables line1 and line2 for each of #fdate and #ftime and then we make some format changes to them.
Finally, we rename file.ext to fileDD-MM-YYYYHH-MM-SS.ext.

Batch File to check text files for a string

im trying to create a batch file that goes thorugh each text file in a folder and looks for specific words such as "msg" "file" "size" in each line. If those words are found then it sends and me an email.
Im using SQL server to send the email, and im calling the email stored procedure from my batch file like this:
set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"
I just need help writing the script which checks for specific words in each line in each .txt file
Just give a try for this batch file :
#echo off
Title Search String into text files
Set "ROOT=%~dp0"
set "String2Search=msg size file"
For %%a in (%String2Search%) do (
FOR /f "delims=" %%f IN ('dir /b /s "%ROOT%\*.txt"') DO (
(find /I "%%a" "%%f" >nul 2>&1) && ( Call :FoundString "%%a" "%%f" ) || ( Call :NoFound "%%a" "%%f" )
)
)
pause & exit
::*************
:FoundString
echo found %1 on file %2
goto :eof
::*************
:NoFound
echo no string like %1 found on file %2
goto :eof
::*************
Few suggestions as i cannot comment.I had done a project few years back and i had to do search files with a particular extension and read them to find particular words and do something with them.I remember few things only.I hope it helps you.
To find all txt files:
find /home/user/Downloads/etc -name '*txt'
To read a whole file and search for "msg" "file" "size":
while read -r LINE
do
grep -i "msg" | grep -i "file" | grep -i "size"
to check all in one line
Or you can do it executing one by one without "pipelining".
P.S I don't have linux installed otherwise I would have checked before posting.Sorry if not correct.
This should do the job:
#ECHO OFF
CD C:\wherever\your\.txt\files\are\at
FOR /R %%G IN ("*.txt") DO (FINDSTR /I /C:"msg" /C:"file" /C:"size" "%%G" >nul && GOTO match_found)
GOTO no_match
:match_found
ECHO Match found^!
set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"
:no_match
ECHO No match found^!
PAUSE
If the batch file is in the same folder as the .txt files you can delete the CD line.
If the search should be case-sensitive remove the /I option.
To satisfy your question as asked, this should suffice:
#Echo Off
FindStr /IR "\<msg\> \<file\> \<size\>" "C:\Users\NT-Hero\*.txt">Nul||Exit /B
Rem Your 'match found' commands here
If you wanted to also search in sub-directories change the FindStr options to /SIR. (See FindStr /? for more options).

Resources