i want to extract tokens from a variable by using / as delimiter.
i used this ::
set fileinput=properties\iam\self_iam_properties.xml
for /f "tokens=*delims=\" %%a in (%fileinput%) do #echo %%a
which gives me following error :
The system cannot find the file properties\iam\self_iam_properties.xml.
why is it searching for a file, i just need to use the value present in the variable. i do not want to take values from a file.
Also after parsing, i wish to create a file named self_iam_parsedoutput.txt so for that i need to extract self_iam_ from the input file name. how to proceed with that ?
Put the %fileinput% in double quotes to treat it like a string.
for /f "tokens=*delims=\" %%a in ("%fileinput%") do #echo %%a
Note that because you're using tokens=*, it won't actually split into multiple variables. If you want each section of the path to get its own variable, you could use something like tokens=1-26
A second way to escape variables in for /f is to run a command which outputs the variable.
for /f %a in ('echo.%variable%')
This form is useful if you're otherwise running into problems with double quotes.
As for the filename change, if the input file is always xyz_properties.xml and the output is always xyz_parsedoutput.txt, then you can use a simple text substitution of the form %variable:old=new%
set inputfile=self_iam_properties.xml
set outputfile=%inputfile:properties.xml=parsedoutput.txt%
Related
Here goes:
I want to add text to a file if it exists. The text is to go on each line of the file at the very end. The text to be added is "Note: certain conditions apply"
I found syntax to check if the file exists, and syntax for a for loop to add text at the end of the line, but they do not seem to work at the same time in the bat file.
Also, advice varies about variable names, using "%" and using the quote marks themselves,
so here is what I have (assume everything takes place in the same directory)....
#echo off
setLocal EnableDelayedExpansion
PAUSE
REM File to be modified -- 1
SET FileToModify1=abcd.txt
SET SaveFile1=abcd1.txt
PAUSE
IF EXIST "%FileToModify1%" (
echo Yes
)
IF EXIST "%FileToModify1%" (
for /f "tokens=* delims= " %%a in "%FileToModify1%" do (
echo %%a Note: certain conditions apply >> "%SaveFile1%"
)
)
PAUSE
Does anyone have a suggestion on what to do here?
Also, is it better to have quotes around abcd.txt or not?
Why all the mysterious "%" around variables?
Please also see loop through file saving to variable for a much more efficient solution to the same problem....
You need this (works):
for /f "tokens=* delims= " %%a in (%FileToModify1%) do (
Where you have (doesn't work, wrong syntax):
for /f "tokens=* delims= " %%a in "%FileToModify1%" do (
From the online help (via for /?)
For file names that contain spaces, you need to quote the filenames with
double quotes. In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.
Also, is it better to have quotes around abcd.txt or not?
It's required if your file name has spaces, otherwise it's optional.Your file name doesn't have spaces so I used the simpler approach, no quotes.
Why all the mysterious "%" around variables?
Well it doesn't have to be "mysterious". Here's an example, from the command line:
> set fname=MyFile.txt
> echo %fname%
MyFile.txt
The %'s around the variable name are seen by the shell and trigger the variable expansion. To see the online help, type set /?, and you'll get more details than you can stand.
Having trouble running a batch file.
SET startIN="D:\Documents and Settings\%USERNAME%\Desktop\DataXfer Helper\StartFolder"
SET collection="D:\Documents and Settings\%USERNAME%\Desktop\DataXfer Helper\StartFolder\*.zip"
FOR /F %%G IN (‘dir /b %collection%\*.zip’) DO “C:\Program Files\Winzip\wzunzip” –E %startIN%\%%G %startIN%
When I type the line at the command prompt - it works fine (the only difference is when typed at the command prompt I use %G instead of %%G).
So, the environement variables are being created properly - but when I run the batch, the single quotes and the hyphen before the E are being turned into other characters (can't identify what they are).
So, any ideas why running the batch would change the characters?
Thank you.
There are a couple of problems:
The symbols in your FOR line are not supported ASCII chars. Retype the ', ", and - in the command line to correct them.
The string expansion is going to include the quotes you set in the path above. For example, %startIN%\%%G will expand to "D:\Documents and Settings\%USERNAME%\Desktop\DataXfer Helper\StartFolder"\MyFile.zip. When dealing with paths, make sure your logic is aware of quotes so they don't get trapped in the middle of the result.
Try updating your script to this:
REM Remove the quotes from the path.
REM Quotes will be added once we know the full path.
SET startIN=D:\Documents and Settings\%USERNAME%\Desktop\DataXfer Helper\StartFolder
REM Quote here because we know the full path.
SET collection="%startIN%\*.zip"
REM Update FOR loop to include parsing options and properly quote output.
REM Also update invalid ASCII chars.
FOR /F "usebackq tokens=* delims=" %%G IN (`dir /b %collection%`) DO "C:\Program Files\Winzip\wzunzip" -E "%startIN%\%%G" "%startIN%"
I have a string contained in a variable, for example:
"C:\Users\SomeUser\Desktop\SomeFolder\File.jar"
I would like to parse File.jar from this string into another variable. I currently have this somewhat working with the code:
FOR /f "tokens=1-6 Delims=\" %%A IN (%string%) DO (set myvariable=%%F)
This works as long as the folder path remains the same length. However, I want to be able to move the program and file and still have everything work right. Is there any way to parse, just as an idea, from right to left? Any advice would be greatly appreciated.
Try to apply path modifiers as follows:
set "inputPath=C:\Users\SomeUser\Desktop\SomeFolder\File.jar"
for %%i in ("%inputPath%") do set fname=%%~nxi
echo %fname%
%%~nx<loop-var> extracts the filename root (n) and filename extension (x) from the loop variable; i.e., it extracts the last/filename component from the loop variable's value.
(%%i was chosen as the loop variable in this case, but any letter will do.)
P.S.: Another frequently used construct is %%~dp<param-or-loop-var-> to extract the drive spec. (d) and the absolute path (without drive spec.) with a terminating \ (p) - this even works for relative input paths.
For instance, %%~dp0 will expand to the absolute path of the folder in which a batch file is located.
A list of all supported path modifiers is here.
(Note that they're only discussed in terms of parameters, but they equally work with for-loop variables).
I suppose you could change the script to process all tokens using *. And since you're setting your variable with the value of each token, at the end the last token will be assigned to the variable.
FOR /f "tokens=* Delims=\" %%A IN (%string%) DO (set myvariable=%%F)
I am trying to create a batch file to input 3 pieces of data and use that data to create another batch file. Just create it, and stop. The batch maps several network drives for users that haaven't a clue as to how to do it.
I have a "master.bat" and using notepad I am using "replace" to fill in the "username" "Password" and "drive path". I thought I would try to get it down to entering the variables into the "master.bat" creating a "custom.bat" for that user.
I got a lot of help here getting to the final step. Everything is working except the final part. Now that I have all the variables as well as a template to put them in, how do I get that first batch file to create the cuctomized output as a workable file that I can send the user where all they do is run it.
One way would be to use your template in file form and replace placeholders in there by your actual values:
setlocal enabledelayedexpansion
for /f %%L in (template.cmd) (
set "Line=%%L"
set "Line=!Line:[username]=!username!"
...
>network-drives.cmd echo !Line!
)
This assumes placeholders like [username] in the template and corresponding variables defined.
However, I always get a little anxious if I use data read from a file in a batch. When I recently had to create a batch file from another I went the following route:
(
echo #echo off
echo net use !drivepath! \\server\share "/user:!username!" "!password!"
echo net use !drivepath2! \\server\share2 "/user:!username!" "!password!"
) > network_drives.cmd
Care has to be taken with things like closing parentheses and several characters reserved for the syntax you may need in the generated batch file. But this approach is entirely self-contained, albeit a little harder to maintain.
It is simple to embed the template within your batch file. There are multiple ways to do this. One is to simply prefix each template line with :::. I chose that sequence because : is already used as a batch label and :: is frequently used as a batch comment.
Delayed expansion can be used to do your search and replace automatically!
There are just 3 special characters you need to worry about if you want to include them in your output. These special characters are probably not needed for the original question. But it is good to know how to handle them in a general sense.
An exclamation literal ! must be either escaped or substituted
A caret literal ^ can be escaped or substituted if it appears on a line with an exclamation. But it must not be escaped if there is not an exclamation on the line. Caret substitution is always safe.
Use substitution to start a line with :
#echo off
setlocal
::The following would be set by your existing script code
set drivePath=x:
set username=rumpelstiltskin
set password=gold
::This is only needed if you want to include ! literals using substitution
set "X=!"
::This is only needed if you want to include ^ literal on same line
::containing ! literal
set "C=^"
::This is only needed if you want to start a line with :
set ":=:"
::This is all that is needed to write your output
setlocal enableDelayedExpansion
>mapDrive.bat (
for /f "tokens=* delims=:" %%A in ('findstr "^:::" "%~f0"') do #echo(%%A
)
::----------- Here begins the template -----------
:::#echo off
:::net use !drivePath! \\server\share "/user:!username!" "!password!"
:::!:!: Use substitution to start a line with a :
:::!:!: The following blank line will be preserved
:::
:::echo Exclamation literal must be escaped ^! or substituted !X!
:::echo Caret with exclamation must be escaped ^^ or substituted !C!
:::echo Caret ^ without exclamation must not be escaped
Question about Batch/Windows/CMD:
I would like that my batch file can search for a line (which I already achieved, but what comes next not), it looks like this:
<name>MyName</name>
It needs to find the text in between <name> and </name>. After that it needs to set that as a variable (%name%).
Does anyone have any idea?
EDIT: if someone wants to give an answer, please list the code. Perl is OK, but this should be open-source and not everyone has Perl.
It can be done this way (assuming your input is in file "test1.html"):
findstr "<name>" test1.html > temp1.lis
FOR /F "tokens=2 delims=>" %%i in (temp1.lis) do #echo %%i > temp2.lis
FOR /F "tokens=1 delims=<" %%i in (temp2.lis) do #echo %%i > temp3.lis
The first line is a guard that only HTML/XML tag
"name" will match in the two FOR lines (you may
already have done this). The result is saved in a temporary
file, "temp1.lis".
The second line capture what is to the right of the first
">" - in effect what is after "<name>". At this stage
"MyName</name" is left in temporary file "temp2.lis" (as
the closing tag also contains ">"). Note the double "%"s
(%%i) as this is in a BAT file (if you want to test directly
from the command line then it should only be one "%").
The third line capture what is to the left of the first "<"
- this is the desired result: "MyName" (is left of "<" in
"MyName</name"). The result is in variable %%i and you
can call a function with %%i as a parameter and access the
result in that function (in the FOR line above the function
was the built-in "echo" and the result thus ended up in
temporary file "temp3.lis" by the redirection of standard
output)
Note that the above only works if
<name>MyName</name>
is the first HTML/XML tag in a line.
If that is not the case or you want a more robust solution
you can instead call a function in the first FOR line (that
receives %%i as the first parameter). That function can then
replace "<name>" with a single character that you are
sure is not in the input, e.g.:
set RLINE=%MYLINE:<name>=£%
Explanation: if the input line is in variable %MYLINE% then
"<name>" will be replaced with "£" and the result will be
assigned to variable %RLINE%.
The reason for the replace is that the delimiters for the
FOR loop are single character only.
You can then use "£" as a delimiter in the FOR loop (to extract what is
to the right of "<name>" - as before):
echo %RLINE%>temp5.lis
FOR /F "tokens=2 delims=£" %%i in (temp5.lis) do #echo %%i > temp6.lis
You have to repeat this technique for "</name>"
(but only if <name>MyName</name> is not
the first HTML/XML tag in a line).
So as you see it is possible, but is quite painful.
Learn Perl, it's made for exactly that kind of thing.