Replace text in csv without uppercase and spaces - batch-file

this script replaces a bit of text within a scv with the filename of the csv.
#echo off
setlocal enableextensions enabledelayedexpansion
for /R %%i in (*.csv) do (
ren "%%~i" temp.tmp
(for /F "usebackq tokens=*" %%f in ("%%~dpitemp.tmp") do (
set "line=%%f"
set "line=!line:REPLACE=%%~ni!"
echo(!line!
)) > "%%~i"
del "%%~dpitemp.tmp"
)
endlocal
So say the file was called CSV File. The text would be replaced with "CSV File". My question is how do i format that text with no spaces or uppercase letters?
So my files called "CSV File", but the replacement is "csv-file". I've tried to strip out the spaces first so I've tried this:
#echo off
setlocal enableextensions enabledelayedexpansion
for /R %%i in (*.csv) do (
ren "%%~i" temp.tmp
(for /F "usebackq tokens=*" %%f in ("%%~dpitemp.tmp") do (
::Tried to strip out the spaces from %%~ni
set %%~ni=%%%~ni: =%
set "line=%%f"
set "line=!line:REPLACE=%%~ni!"
echo(!line!
)) > "%%~i"
del "%%~dpitemp.tmp"
)
endlocal
Doesn't work with that, anyone know why? I did get this working:
set "line=!line: =-!"
But I can't do that as it'll effect the whole csv. So I'm not sure if there's a way to tell that line to just effect the replacment text?
Edited code:
#echo off
setlocal enableextensions enabledelayedexpansion
for /R %%i in (*.csv) do (
ren "%%~i" temp.tmp
(for /F "usebackq tokens=*" %%f in ("%%~dpitemp.tmp") do (
set "line=%%f"
echo %%~ni
set MyVar=%%~ni
set MyVar=!MyVar: =-!
set MyVar=!MyVar:,=!
echo !MyVar!
set "line=!line:REPLACE=!MyVar!!"
echo(!line!
)) > "%%~i"
del "%%~dpitemp.tmp"
)
I've managed to strip out the spaces and a comma, so just working on how to get that !MyVar! in my replacement.

I'd use powershell as a tool for this.
From cmdline:
> type "TEST FILE.CSV"
One,two,three
bla,REPLACE,blubb
REPLACE,test,blah
tralala,blah,REPLACE
> for /f "delims=" %A in ('Dir /B/S "test*.csv"') do #powershell -Nop -c "(Get-Content '%~fA') -Replace 'REPLACE',('%~nxA').Replace(' ','-').ToLower()|Set-Content '%~fA'"
> type "TEST FILE.CSV"
One,two,three
bla,test-file.csv,blubb
test-file.csv,test,blah
tralala,blah,test-file.csv
In a batch file double the %-signs
#Echo off
for /f "delims=" %%A in (
'Dir /B/S "test*.csv"'
) do powershell -Nop -c "(Get-Content '%%~fA') -Replace 'REPLACE',('%%~nxA').Replace(' ','-').ToLower()|Set-Content '%%~fA'"

Related

Stripping characters out of variable

I'm trying to strip spaces and commas from %%~ni. I've managed to do it by putting it into my new variable !url!. It echos fine, but does anyone know why I can't use it here: set "line=!line:REPLACE=!url!!" ?
#echo off
setlocal enableextensions enabledelayedexpansion
for /R %%i in (*.csv) do (
ren "%%~i" temp.tmp
(for /F "usebackq tokens=*" %%f in ("%%~dpitemp.tmp") do (
set "line=%%f"
echo %%~ni
set url=%%~ni
set url=!url: =-!
set url=!url:,=!
echo !url!
set "line=!line:REPLACE=!url!!"
echo(!line!
)) > "%%~i"
del "%%~dpitemp.tmp"
)
Answer for anyone else having this problem:
#echo off
setlocal enableextensions enabledelayedexpansion
for /R %%i in (*.csv) do (
ren "%%~i" temp.tmp
(for /F "usebackq tokens=*" %%f in ("%%~dpitemp.tmp") do (
set "line=%%f"
set url=%%~ni
set "url=!url: =-!"
set "url=!url:,=!"
set "url=!url:(=!"
set "url=!url:)=!"
for /F "delims=" %%e in ("!url!") do set "line=!line:REPLACE=%%e!"
echo(!line!
)) > "%%~i"
del "%%~dpitemp.tmp"
)

batch file remove X characters of filename

I did batch file which copy 3 files and need to rename it by removing last 33 characters. The copy works fine but removing last 33 characters not... I saw more then one answer on web and try it all but nothing work so far.
My batch file look like this:
for /f "delims=" %%i in ("my folder") do (
ren "%%i" "%i:~0,-33%".txt
)
I tried already:
set fName=%%i
ren "%fName%" "%fName:~0,-33%.txt"
From the information I got here, try this:
#echo off
setlocal enabledelayedexpansion
set "folderpath=[Your Folder Here...]"
cd %folderpath%
for /f %%a in ('dir /b "*.txt"') do (
set "fname=%%~na"
ren "%%a" "!fname:~0,-33!.txt"
)
endlocal
This is similar to the answer above. You should make sure the batch file is OUTSIDE the folder.
EDIT.
When dealing with variables formed inside FOR and IF's, use delayed expansion (i.e. !var!, instead of %var%). Anyway, this is the fixed code:
#echo off
setlocal enabledelayedexpansion
::NO Last Backslash...
set "sourcepath=C:\Users\tzahi.k\Desktop\testSource\source2"
set "folderpath=C:\Users\tzahi.k\Desktop\testSource\des"
for /F "delims=" %%a in ('dir /b /od "%sourcepath%\*.txt"') do (
set "youngest=%%a"
xcopy /y "%sourcepath%\!youngest!" "%folderpath%"
)
cd /d %folderpath%
for /f %%a in ('dir /b "*.txt"') do (
set "fname=%%~na"
ren "%%a" "!fname:~0,-33!.txt"
)
endlocal
pause
Here's the batch file you'd want to run:
#echo off
Setlocal EnableDelayedExpansion
#for /f "delims=" %%i in ('dir /b *.txt') do (
set fname=%%~ni
set fname=!fname:~0,-33!.txt
ren "%%i" "!fname!"
)
endlocal
This should work
#echo off
setlocal enabledelayedexpansion
set FOLDER_PATH=C:\Some\Path\
for %%f in (%FOLDER_PATH%*) do if %%f neq %~nx0 (
set "filename=%%~nf"
ren "%%f" "!filename:~0,-33!%%~xf"
)
PAUSE
Or better this
#echo off & setLocal enableDELAYedeXpansion
for /f "tokens=* delims= " %%a in ('dir /b *.txt') do (
set F=%%~Na
set F=!F:~0,33!
move /y "%%a" "!F!%%~Xa"
)

How to set name of final output .csv file to the name of the folder?

I have a working Windows batch script which combines multiple CSV files with same headers into one big CSV file. It is as follows:
#echo off
ECHO Set working directory
pushd %~dp0
ECHO Deleting existing combined file
del combined.csv
setlocal ENABLEDELAYEDEXPANSION
set cnt=1
for %%i in (*.csv) do (
if !cnt!==1 (
for /f "delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
) else if %%i NEQ combined.csv (
for /f "skip=1 delims=" %%j in ('type "%%i"') do echo %%j >> combined.csv
)
set /a cnt+=1
)
I want the output file to be the same name as the folder name, instead of combined.csv.
For example, if the name of the folder is ABC, then output combined CSV file should be ABC.csv.
#echo off
setlocal enableextensions disabledelayedexpansion
pushd "%~dp0"
set "first=1"
for %%a in ("%~dp0\.") do (
del "%%~nxa.csv" 2>nul
(for %%i in (*.csv) do (
if /i not "%%~nxi"=="%%~nxa.csv" if defined first (
set "first="
type "%%~fi"
) else (
(for /f "skip=1 usebackq delims=" %%j in ("%%~fi") do echo(%%j)
)
)) > "%%~fa\%%~nxa.csv"
)

Insert new lines(which has a command) after a particular line in batch file using batch file

I want to insert a line which has a command(mkdir/copy) in a batch file after a particular line using a batch file.(mkdir/copy command should be considered as a word rather than command)
Input:
set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB
copy /Y %QBprovisionpath%\x86\Debug %ConnectorExecutionPath%\x86\Debug
Output:
set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB
copy /Y %ConnectorExecutionPath%\%outqbsyncpath%
mkdir /Y %ConnectorExecutionPath%\%outqbsyncpath%
copy /Y %QBprovisionpath%\x86\Debug %ConnectorExecutionPath%\x86\Debug
A New line copy /Y %ConnectorExecutionPath%\%outqbsyncpath% - which has a copy command and mkdir /Y %ConnectorExecutionPath%\%outqbsyncpath% which has mkdir command, get inserted after a particular line set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB
SETLOCAL ENABLEDELAYEDEXPANSION
set inputFile=%userprofile%\desktop\testSO.bat
set outputFile=%userprofile%\desktop\testSOout.bat
set _strInsert=set IndbBankpath=C:\InstallerOutput\QuickBooks-Sync\indb
set _strFind=set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB
set i=0
FOR /F "usebackq tokens=1 delims=[]" %%A IN (FIND /N "%_strFind%" "%inputFile%") DO (set _strNum=%%A)
FOR /F "usebackq delims=" %%A IN ("%inputFile%") DO (
set /a i = !i! + 1
ECHO %%A>>"%outputFile%"
IF [!i!] == [%_strNum%] (
ECHO %_strInsert%>>"%outputFile%"
ECHO I WANT TO ADD THIS LINE ALSO>>"%outputFile%"
ECHO OOOO THIS LiNE TOO>>"%outputFile%"
ECHO ZOMGBBQSAUCE ADD THIS LINE ALSO>>"%outputFile%"
)
)
The above code doesn't work if I change set _strInsert=copy /Y %ConnectorExecutionPath%\%outqbsyncpath% or set _strInsert=mkdir %ConnectorExecutionPath%\%outqbsyncpath%
Please suggest a solution for this.
#echo off
set "particularLine=set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB"
setlocal DisableDelayedExpansion
if exist output.bat del output.bat
for /F "delims=" %%a in (input.bat) do (
echo %%a
set "line=%%a"
setlocal EnableDelayedExpansion
if "!line!" == "!particularLine!" (
echo copy /Y %%ConnectorExecutionPath%%\%%outqbsyncpath%%
echo mkdir /Y %%ConnectorExecutionPath%%\%%outqbsyncpath%%
)
endlocal
) >> output.bat
Previous Batch file has several drawbacks: it remove empty lines and may fail if the line contain quotes.
EDIT: New version added
The Batch file below run faster if the input file is large; it also have several details fixed, like not removing empty lines.
#echo off
setlocal EnableDelayedExpansion
set "inputFile=%userprofile%\desktop\testSO.bat"
set "outputFile=%userprofile%\desktop\testSOout.bat"
set "particularLine=set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB"
for /F "usebackq delims=:" %%a in (`findstr /N /C:"!particularLine!" "%inputFile%"`) do set theLine=%%a
if exist "%outputFile%" del "%outputFile%"
if not defined theLine echo The particular line doesn't exist in Input file & exit /B
setlocal DisableDelayedExpansion
set i=0
for /F "usebackq delims=" %%a in (`findstr /N "^" "%inputFile%"`) do (
set "line=%%a"
set /A i+=1
setlocal EnableDelayedExpansion
echo(!line:*:=!
if !i! eql %theLine% goto exitLoop
endlocal
) >> "%outputFile%"
:exitLoop
rem Insert here all the lines to insert, each one preceeded by ECHO
(
echo copy /Y "%%ConnectorExecutionPath%%\%%outqbsyncpath%%"
echo mkdir /Y "%%ConnectorExecutionPath%%\%%outqbsyncpath%%"
) >> "%outputFile%"
setlocal DisableDelayedExpansion
for /F "skip=%theLine% usebackq delims=" %%a in (`findstr /N "^" "%inputFile%"`) do (
set "line=%%a"
setlocal EnableDelayedExpansion
echo(!line:*:=!
endlocal
) >> "%outputFile%"
Please note that you must double the percent signs in the commands to insert; otherwise what is inserted is the current value of the variables instead of the %name% of the variables.
I believe the only problem you're running into is the fact that you're not encapsulating your paths for the COPY and MKDIR commands:
set _strInsert=mkdir %ConnectorExecutionPath%\%outqbsyncpath%
Try:
set _strInsert=mkdir "%ConnectorExecutionPath%\%outqbsyncpath%"
I would also do a check for the folder before creating it as well.
EDIT:
Now if you're adding in a bunch of different lines, just add them to the code. In your previous post you asked to add a single line to the code. If you're doing multiple lines, just echo them directly into the output file.
SETLOCAL ENABLEDELAYEDEXPANSION
set inputFile=%userprofile%\desktop\testSO.bat
set outputFile=%userprofile%\desktop\testSOout.bat
set _strFind=set MTBBankpath=C:\InstallerOutput\QuickBooks-Sync\MTB
set i=0
FOR /F "usebackq tokens=1 delims=[]" %%A IN (FIND /N "%_strFind%" "%inputFile%") DO (set _strNum=%%A)
FOR /F "usebackq delims=" %%A IN ("%inputFile%") DO (
set /a i = !i! + 1
ECHO %%A>>"%outputFile%"
IF [!i!] == [%_strNum%] (
ECHO set IndbBankpath=C:\InstallerOutput\QuickBooks-Sync\indb
ECHO copy /Y "%ConnectorExecutionPath%\%outqbsyncpath%"
ECHO mkdir /Y "%ConnectorExecutionPath%\%outqbsyncpath%"
ECHO copy /Y "%QBprovisionpath%\x86\Debug %ConnectorExecutionPath%\x86\Debug"
)>>"%outputFile%"
)

How to get a Substring from list of file names

I want to develop the following logic
Read all files in a directory
Extract the first part of the filename – this will be the partner name
Extract anything after the first underscore- this will be filename
Eg: ZZTEST_123_abc_doc.txt  ZZTEST is partner. 123_abc_doc.txt is the filename.
Below is the code I developed
#echo off
setlocal ENABLEDELAYEDEXPANSION
Set Test_Dir=C:\Axway\projects\Cardinal\dosscript\test
cd %Test_Dir%
for /r %%a in (*.*) do (
Set "fname1=%%~nxa"
echo Filename is :!fname1!
for /f "tokens=1 delims=_" %%i in ("!fname1!") do (
Set "partner=%%i"
echo Partner is :!partner!
Set "str_tmp=!partner!_"
echo !str_tmp!
call :strlength length !str_tmp!
echo !length!
set fname=!fname1:~%length%!
echo !fname1:~%length%!
)
)
goto :eof
:strlength
setlocal enableextensions
set "#=%~2"
set length=0
:stringLengthLoop
if defined # (set "#=%#:~1%"&set /A length+=1&goto stringLengthLoop)
endlocal && set "%~1=%length%"
GOTO :EOF
But the result is
ID_ZZRoutingID_filename.txt
Filename is :ZZRoutingID_ZZRoutingID_filename1.txt
Partner is :ZZRoutingID
12
Result: ID_ZZRoutingID_filename1.txt
The result should be ZZRoutingID_filename1.txt but i am getting
ID_ZZRoutingID_filename1.txt.
Please help
The purpose of the length calculation is not clear to me, but I would suggest adding an asterisk following the 1 in your for /f "tokens=1 delims=_". You would then get the "filename" you were looking for through %%j.
I tested it like this:
#echo off
setlocal EnableDelayedExpansion
set source=D:\Program Files\Somewhere
cd %source%
for /r %%i in (*.*) do (
for /f "tokens=1* delims=_" %%j in ( "%%~nxi" ) do (
echo partner: %%j
echo name: %%k
)
)
endlocal
If you do not need to recurse through sub-directories:
#echo off
set source=D:\Program Files\Somewhere
for /f "tokens=1* delims=_" %%i in ( 'dir "%source%" /b /a-d' ) do (
echo partner: %%i
echo filename: %%j
)
dir /b /a-d retrieves the list of a directory's content except its sub-directories:
D:\Program Files\Somewhere>dir /b /a-d
ZZTEST_123_456.txt
ABCDEF_890_FFF.doc
FOOBAR_567_###.zzz

Resources