Add commas to txt file from batch script in Windows - windows

I have this format on a .txt file:
"Rosina Merola (rosina_merola#hotmail.com)" <rosina_merola#hotmail.com>
"Sabina Morales (sabinamorales#gmail.com)" <sabinamorales#gmail.com>
"Sorella Blanco (zoreblanco#hotmail.com)" <zoreblanco#hotmail.com>
"Eduardo Schmilinsky Leal" <ejsl41#hotmail.com>
"Elba Rodríguez" <elbameister#gmail.com>
Ernesto Ramirez <ernestoramirezricca#hotmail.com>
Some of the names have ""and a few don't, as you can see in this example.
However, i need to add a comma ',' after each name and before the email line <>
I thought that first adding the "" to every name, it could be easier then to add the commas, i have this code:
#echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (nombresemails.txt) do (
echo "%%a", >> nombresemailscomillas.txt
)
It works but it adds the "" in this format:
"Adam Podlinski <apodlinski#cantv.net> ",
"Adam Podlinski 2 <apodlinski#yahoo.com>",
""Aldo Gonzalez " <aldodanielg#hotmail.com>",
""Alejandr Rubin" <rubin4#cantv.net>",
""Alfredo Huguett " <alfredohuguettc#hotmail.com>",
""aainiguezf#gmail.com" <aainiguezf#gmail.com>",
No matter what are the characters it just adds the "" even if they already have it, and besides, it adds them to all the line, i just need to add them to every name, leaving the emails inside the <> without the "".
Anyway, this is just an approach i thought it could work, basically i just need to add a comma after every name and before the emails cointained in <>
there is actually some way achieve this on batch code?
Thanks in advance!

This works here:
#echo off
setLocal EnableDelayedExpansion
for /f "delims=" %%a in (nombresemails.txt) do (
set "line=%%a"
set "line=!line: <=,<!"
>>nombresemailscomillas.txt echo !line!
)

Related

Batch file to insert string in exact position in file txt

I have a test.txt file like this:
sylvester, stallone, 35,20, florida;
brad, pitt, 40,25, california;
sean, connery, 15,80, london;
I have to create a new one in which the surname begins with the 15th column and the name in the 30th.
I would like to do it with a batch file.
What I have managed to do is this:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=1,2 delims=," %%G IN (test.txt) DO (
SET "line=%%H"
SET "spaces= "
ECHO (!spaces!!line!!spaces!%%G
)
) >> output.txt
pause
But in this way %%G does not begin always from the same position, it depends on how many characters has %%H. And more, does not write on output.txt but it makes me see the results on the batch window.
I know it's probably a trivial question, but I'm new to programming.
#echo off
setlocal enabledelayedexpansion
del output.txt
set "spaces= " :: 15 spaces
(FOR /F "tokens=1,2 delims=, " %%G IN (test.txt) DO (
SET "line=%spaces%%%H %spaces%"
set "line=!line:~0,29!"
echo !line:~0,29!%%G
)) >output.txt
add 14 spaces in front of the surname (to let surename start at 15) and append another 15 spaces (to get a cumulated length of at least 29). Then trim it to the first 29 characters and append the name (at Pos 30).
(added a space to the delims for proper handling)

Windows Batch - Find word in one string matching word in another string and capture output

While this may seem easy to some, I've struggled for hours on it.
I have a file:
MYFOLDER,JobE,JobD_ENDED_OK,
MYFOLDER,JobD,JobC_ENDED_OK,JobD_ENDED_OK
MYFOLDER,JobD,JobB_ENDED_OK,
MYFOLDER,JobC,JobA_ENDED_OK,JobC_ENDED_OK
MYFOLDER,JobB,JobA_ENDED_OK,JobB_ENDED_OK
MYFOLDER,JobA,,JobA_ENDED_OK
I need to loop through and find where token 4 in one line matches token 3 in another line and then echo a statement to a file. I am looking for an output file that shows this:
MYFOLDER_JobA_MYFOLDER_JobB matches JobA_ENDED_OK
MYFOLDER_JobA_MYFOLDER_JobC matches JobA_ENDED_OK
MYFOLDER_JobB_MYFOLDER_JobD matches JobB_ENDED_OK
MYFOLDER_JobC_MYFOLDER_JobD matches JobC_ENDED_OK
MYFOLDER_JobD_MYFOLDER_JobE matches JobD_ENDED_OK
I know it's a FOR loop with a DO, I am just not getting the rest of it.
Any assistance is greatly appreciated.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q46510665.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "usebackqdelims=" %%h IN ("%filename1%") DO (
SET "col4line=%%h"
SET "col4line=!col4line:,=|,|!"
FOR /f "tokens=1-4delims=," %%a IN ("!col4line!") DO IF "%%d" neq "|" (
FOR /f "usebackqdelims=" %%H IN ("%filename1%") DO (
SET "col3line=%%H"
SET "col3line=!col3line:,=|,|!"
FOR /f "tokens=1-4delims=," %%A IN ("!col3line!") DO (
IF "%%d|"=="%%C" (
SET "reportline=%%a_%%b_%%A_%%B matches %%C"
ECHO !reportline:^|=!
)
)
)
)
)
)>"%outfile%"
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances.
I used a file named q46510665.txt containing your data for my testing.
Produces the file defined as %outfile%
For each line in the file, set a variable col4line to the entire line via %%h, then replace each , with |,| so that successive , will be separated. Tokenise on , and ignore any line which has simply | as its 4th token (ie last-column-empty).
Repeat the process for every line in the file this time through %%H into col3line (note case differential to use different actual metavariables) and if the third column matches the fourth column+| from the outer loop, assemble the report line from the tokens and output, removing the |s.

Batch script extract contents between two strings

I am trying to write this Batch script to extract the two parameters from an XML file that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<!--<var name="SqlConnection" value="data source=SERVERNAME;initialcatalog=DB_NAME;user id=JackDaniels;password=G235X" />-->
<var name="SqlConnection" value="data source=SERVERNAME;initial catalog=DB_Name;Integrated Security=SSPI" />
My objective is to extract SERVERNAME and DB_NAME from the line that is not commented out.
So far my code looks like this:
#echo off
setlocal enableextensions disabledelayedexpansion
set "connectionString="
set result=""
set "INPUT_FILE=DBConnection.config"
FOR /F "tokens=* delims=<var eol=!" %%x in (%INPUT_FILE%) DO (
ECHO %%x
)
PAUSE
I'm just not sure how to get everything right after "data source=" and "initial catalog=". Is there an easy way to do this?
The adequate way to extract this data is not via a Batch file, but with the methods suggested in a comment. However, the Batch file below perform this extraction in a relatively simple way:
#echo off
setlocal EnableDelayedExpansion
rem From the line that have "<var" followed by "value"...
for /F "delims=" %%a in ('findstr "\<var.*value" input.txt') do (
rem ... process the parts separated by space or equal sign, excepting if enclosed in quotes...
for %%b in (%%a) do (
rem ... and store the part after "value" variable
if "!var!" equ "value" set "value=%%~b"
set "var=%%~b"
)
)
rem Separate "value" string at semicolons and assign each part via SET command
for %%a in ("%value:;=" "%") do set %%a
rem Show results:
echo data source=%data source%
echo initial catalog=%initial catalog%
echo Integrated Security=%Integrated Security%
Output example:
data source=SERVERNAME
initial catalog=DB_Name
Integrated Security=SSPI
Of course, if the data format described in the code changes, the program will fail...
#ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q42420941.txt"
FOR %%v IN (initial catalog data source initial_catalog data_source) DO SET "%%v="
FOR /f "delims=<>" %%z IN ('findstr /B /L /C:"\<var name" "%filename1%"') DO (
FOR %%y IN (%%z) DO (
FOR %%a IN (%%~y) DO (
SET "alive=Y"
FOR %%m IN (initial catalog data source) DO IF /i "%%a"=="%%m" SET "alive="&set %%a=Y
IF DEFINED alive (
IF DEFINED initial IF DEFINED catalog SET "initial_catalog=%%a"
IF DEFINED data IF DEFINED source SET "data_source=%%a"
)
IF DEFINED catalog IF NOT DEFINED initial SET alive=y
IF DEFINED source IF NOT DEFINED data SET alive=y
IF DEFINED alive FOR %%v IN (initial catalog data source) DO set "%%v="
)
)
)
ECHO %initial_catalog% and %data_source%
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named q42420941.txt containing your data for my testing.
first, clear out the variable-names.
next, parse each line that passes the findstr which is looking for lines that /L literally /B begin with the /c: character-sequence "< escaped by \) and take the first token delimited by > or <.
This neatly strips the awkward <> from the string and assigns the contents of the selected line to %%z
Next, use a simple for to present each token in the line to %%y.
Then with the quotes stripped off of %%y assign each token to %%a.
Search for a match against the keywords, and set the variable of the same name if found. Clear alive if a keyword is found.
If the string in %%a is not one of the keywords, then check to see whether initial and catalog are both set. If so, this is the required string, so assign it.
if catalog is found but not initial then mark as alive
If alive is still set, then we can clear the flags and wait for the start of another sequence.
OK - it has its faults. It won't detect initial_catalog/data_source if either is one of the four keywords (unlikely) and it assumes that the wanted data is the token following the two keywords - the = becomes a separator in the for list.
Since many of you suggested that Batch is not an adequate way of doing this, I decided to play around with PowerShell, and was able to accomplish what I wanted with just a few lines, and some Regex!
$configPath = $PSScriptRoot + "DBConnection.config"
[xml]$XmlDocument = Get-Content -Path $configPath
$dataSource = $XmlDocument.var.Attributes[1].Value.ToString() # Extract the uncommented line, and the second attribute "value"
$serverName = ($dataSource -split 'data source=([^;]*);')[1]
$db_name = ($dataSource -split 'initial catalog=([^;]*);')[1]
$user_id = ($dataSource -split 'id=([^;]*);')[1]
$user_pass = ($dataSource -split 'password=([^;]*)')[1]

Batch - String replacement with special characters

I would like to replace a string in a file using a batch file.
The string is:
),(
And I want to replace it by:
),
(
I found several posts, like this one : "how-to-replace-substrings-in-windows-batch-file" but the example uses a dummy string with no special characters.
Thank you !
EDIT
Context: I use mysqldump to extract a database and I would like every line of the insert command to be on a new line for more visibility.
I don't want to use --extended-insert=false because it slows down reinsertion of the backup.
EDIT2
Example:
INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),(2),(3);
I want it to be:
INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),
(2),
(3);
Take a look at replacer.bat
call replacer.bat "e?C:\content.txt" "\u0022),(\u0022" "\u0022),\u000a(\u0022"
Edit without the quotes:
call replacer.bat "e?C:\content.txt" "),(" "),\u000a("
windows style
call replacer.bat "e?C:\content.txt" "),(" "),\u000D\u000a("
you can check also FindRepl and JRepl which are more sophisticated tools
This works for me:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET textFile=test.txt
TYPE NUL>tempOut.txt
FOR /F %%l IN (%textFile%) DO (
SET line=%%l
SET line=!line:"),("="),\n("!
ECHO !line!>>tempOut.txt
)
MOVE /y tempOut.txt %textFile%
In batch if the pattern are always same you could deal with tokens and delims like this:
#echo off
(echo INSERT INTO `dummytable` (`dummycolumn`^) VALUES (1^),(2^),(3^);
)>%TEMP%\_file.tmp
(FOR /F "tokens=1,2,3* delims=," %%a IN (%TEMP%\_file.tmp) do (
echo %%a,
echo %%b,
echo %%c
))>_output.txt
exit /b 0
output:
INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),
(2),
(3);
Edit
I found another way from a npocmaka's post in stackoverflow
#echo off
setlocal disableDelayedExpansion
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^
set NL=^^^%NLM%%NLM%^%NLM%%NLM%
setlocal enableDelayedExpansion
for /f "delims=" %%a in (%TEMP%\_file.tmp) do (
set "line=%%a"
set line=!line:,(=,%NL%(!
echo !line!
)
endlocal
endlocal
exit /b 0

Remove first and last character from a String in a Windows Batch file

I have the following string inside my Windows batch file:
"-String"
The string also contains the twoe quotation marks at the beginning and at the end of the string, so as it is written above.
I want to strip the first and last characters so that I get the following string:
-String
I tried this:
set currentParameter="-String"
echo %currentParameter:~1,-1%
This prints out the string as it should be:
-String
But when I try to store the edited string like this, it fails:
set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%
Nothing gets printed out. What do I do wrong?
This really is strange. When I remove the characters like this it works:
set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%
it prints out:
-String
But actually my batch is a bit more complicated and there it does not work. I will show what I programmed:
#echo off
set string="-String","-String2"
Set count=0
For %%j in (%string%) Do Set /A count+=1
FOR /L %%H IN (1,1,%COUNT%) DO (
echo .
call :myFunc %%H
)
exit /b
:myFunc
FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (
echo String WITHOUT stripping characters: %%I
set currentParameter=%%I
set currentParameter=%currentParameter:~1,-1%
echo String WITH stripping characters: %currentParameter%
echo .
)
exit /b
:end
And the output is:
.
String WITHOUT stripping characters: "-String"
String WITH stripping characters:
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: ~1,-1
.
But what i want is:
.
String WITHOUT stripping characters: "-String"
String WITH stripping characters: -String
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: -String2
.
Hope this will help you.
setlocal enabledelayedexpansion
echo String WITHOUT stripping characters: %%I
set currentParameter=%%I
set currentParameter=!currentParameter:~1,-1!
echo String WITH stripping characters: !currentParameter!
You are modyfing a variable inside a parenthesized block. Watch out - the new value will not be used within the same block (unless you delimit the variable with ! instead of % - and running in the enabledelayedexpansion mode).
Or just extract the couple of lines into another sub-function, using a plain sequence of lines insted of ( )
greets, Stach
This script takes advantage of ENABLEDELAYEDEXPANSION.
If you don't know, batch scripts execute for and if commands all in one; hence if you do:
if true==true (
#echo off
set testvalue=123
echo %testvalue%
pause >NUL
)
You wont output anything, because when echo %testvalue% is executed, it has not recognized the testvalue has been changed.
Using delayedexapnsion allows the script to read that value as it is now, and forget the problem I stated before. You use it just like %testvalue%, but you may do !testvalue! to fix this:
if true==true (
#echo off
set testvalue=123
echo !testvalue!
pause >NUL
)
Would echo 123.
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set string="-String","-String2"
Set count=0
For %%j in (%string%) Do Set /A count+=1
FOR /L %%H IN (1,1,%COUNT%) DO (
echo .
call :myFunc %%H
)
exit /b
:myFunc
FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (
echo String WITHOUT stripping characters: %%I
set currentParameter=%%I
set currentParameter=!currentParameter:~1,-1!
echo String WITH stripping characters: !currentParameter!
echo .
)
exit /b
:end
~ Alex
I had similar problem but it solved by removing spaces between
Ex : set FileName=%Name:~0,11% # Working as No space before and after '='
Ex : set FileName = %Name:~0,11% # Not Working as space before OR after '='
So please try by remove spaces, It should work
Note: command line should be reopen to get refresh the background values else it shows the same output as it is stored in temp

Resources