How to get a substring with special characters in batch file? - string

I'm trying to remove a part of a string with special characters.
The string looks like: <abc>123</abc>
I want to extract only 123
I've tried
set substr=<abc>
%my_string:substr=%
and removing character by position
set result=%my_string:~5,-6%
but neither works. Someone can help me?
ps. I'm new in batch.
sorry for the english.

Delayed expansion and double quoting of strings are the methods needed here.
The use of the for loop is just as a way of defining all substrings to be removed in the one line.
#echo off
Setlocal enabledelayedexpansion
set "string=<abc>123</abc>"
For %%A in ("<abc>" "</abc>") do Set "string=!string:%%~A=!"
Echo(!string!
pause

Related

Remove string upto the first occurrence of a character using batch script

I have a variable say
var="dev02,qa02,stage,prod,dev02_loc,qa02_loc,stage_loc,prod_loc"
I need to convert this into
qa02,stage,prod,dev02_loc,qa02_loc,stage_loc,prod_loc
by removing all the characters before the first occurence of ,
How can I do this using batch script?
What you can do is to use variable expansion and substitution.
In this case given your stated variable content of:
dev02,qa02,stage,prod,dev02_loc,qa02_loc,stage_loc,prod_loc
You could simply expand the variable, substituting everything up to the first comma with nothing:
Echo(%var:*,=%
For setting your initial variable, %var%, you should change the syntax to this:
Set "var=dev02,qa02,stage,prod,dev02_loc,qa02_loc,stage_loc,prod_loc"
This will prevent the doublequotes from being included in the variable value, prevent accidental trailing whitespace and protect the content.
You can use a for loop (see for /?) delimit on , and do something with the result:
#set "var=dev02,qa02,stage,prod,dev02_loc,qa02_loc,stage_loc,prod_loc"
#for /f "tokens=1* delims=," %%i in ("%var%") do #echo(%%j

Split string by special characters '*' in batch file

I need to delete the substring after *. with a batch file
Example :
The value of string is : TEST_SINISTRE*.csv
rem My code :
SET mystring="TEST_SINISTRE*.csv"
rem Do the split
SET ext_test=%mystring:*.="& rem %"
SET ext_test=%ext_test%
rem what i get
echo %ext_test% ===> "& rem csv"
rem What i want to see
===> TEST_SINISTRE
Can you help me :-)
If, and only if, the *. pattern can only occur once in the string, and the part after *. is not contained in the part before *., the following could be used:
rem this is the original string containing one `*.`:
set "STRING=TEST_SINISTRE*.csv"
rem now get everything after `*.`:
rem (if `*` is the first character in substring substitution, it means everything up to
rem and including the search string is to be replaced, by nothing here in this case)
set "SUBSTR=%STRING:**.=%"
rem get everything before `*.`, including the `*`:
setlocal EnableDelayedExpansion
set "SUBSTL=!STRING:.%SUBSTR%=!"
rem truncate the `*` from the string:
endlocal & set "SUBSTL=%SUBSTL:~,-1%"
Since the substitution syntax for variable expansion is used, this is done in a case-insensitive manner.
To make it more secure, you could append something that will most probably never occur to your original string temporarily and remove it afterwards. To accomplish this, replace the set command line between the setlocal/endlocal block with the following (using appendix ### here for instance):
set "STRING=!STRING!###"
set "SUBSTL=!STRING:.%SUBSTR%###=!"
The * character is a wildcard in batch variable substring substitution. When you do *.=something in an inline substitution, you're really saying "replace everything up to and including the dot". You should use a for /F loop so you can specify the asterisk as a delimiter.
set "str=TEST_SINISTRE*.csv"
for /f "tokens=1* delims=*" %%I in ("%str%") do set "ext_test=%%I%%J"
echo %ext_test%
I'm not sure what your ultimate goal is, but here's a hacksy possible alternative. You could actually create a file called TEST_SINISTRE.csv and then capture the filename into a variable as a wildcard match.
set "str=TEST_SINISTRE*.csv"
type NUL > TEST_SINSTRE.CSV
for %%I in (%str%) do set "ext_test=%%I"
echo %ext_test%
I'm sure that's not exactly you have in mind, but it does demonstrate that maybe you don't need to strip the asterisk if you are going to be performing filename matching.

Batch String Manipulation

I am trying to write a batch program that writes more code based on what the user inputs. I am stuck on the string manipulation, as "!", ">", "&", and "%" all need to be escapeded before they are to be outputted to other files. This is what I have so far:
#echo off
set /p code=
set newcode=%code:^%=^%%,^>=^^>,!=^^!,^&=^^&%
echo %newcode%>>file.bat
All this escapinging escaped stuff is making my brain hurt, so can you please help me?
Thanks!
Since you haven't explained clearly what you are trying to do with the input, I am assuming you are trying to get the user to type something and then for that to be entered into a file. If that is the case te utilise copy in combination with con
#echo off
Echo Enter ^^Z (Ctrl + Z) and return it to end input
copy con file.txt
And that will allow the user to type WHATEVER they want, and it to be put in a file to be examined. Otherwise you're gonna have a lot of fun (And trouble) dealing with all the escaping you're gonna have to do (Rather ironic wasn't that?).
Mona.
Simply use delayed expansion in your case, as delayed expansion needs no further escaping for the content.
#echo off
setlocal EnableDelayedExpansion
set /p code=
echo(!code!
The echo( is for safe text output, even if the text is empty or is something like /?.
To the comment of #foxidrive:
When delayed expansion is enabled, then exclamation marks ! are altered, when they are visible before the delayed expansion is done, but the expanded content of delayed expanded variables will never be altered.
#echo off
set "var=Hello!"
setlocal EnableDelayedExpansion
echo "!var!" "Hello!"
This will result to: "Hello!" "Hello"

shorten every line in a text file by exactly 59 charaters then add a new shorter string in their place

For something so simple that can easily be done with find replace in notepad, I can't see why it is so hard to do in a command line as it is just one step in the entire procedure that I would like to get down to a single run. The output from the first part lists the local path to all the websites in the webserver as the each local path c:/ etc. every site has the same 59 characters before the part that matters.
To make this a usable link, I need to then add a different string in the same position as the old one with the correct http://. etc. to the balance of the line to make it a working hyperlink.
The final step needs to convert any single "\’s" that are left to a "/". Normally there is only one
All of this can be done in notepad++ using find and replace but it takes 3 runs to achieve the end result the original text file is nothing special, no skipped lines, everyone is identical in layout.
The same 59 characters need to be chopped off (it could even be by Number and not by comparing the text, just shorten by 59 characters if that is easier. The replacement text string is always exactly the same that just gets appended to each line. And for the final touch of replacing every \ with a / to make it fully web-compatible there is only one occurrence on each line.
I have seen many find and replace batch-files that seem to be overkill for such a simple task.
Take each line, count fifty nine characters forward, chop off the 59 and add in the replacement text in its place.
Then change the only backslash in the line to a forward slash and it’s done
Does anyone know a simpler easier way to do this
This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat in the same folder as the batch file or in a folder that is on the path.
Just change http://www.domain.com/ to what you need to prefix the lines with.
type "file.txt" | repl "\\" "/" | repl "^.{59}" "http://www.domain.com/" >"newfile.txt"
The two \\ are intentional as it is a regular expression.
#ECHO OFF
SETLOCAL
(
FOR /f "delims=" %%a IN (Q21495128.txt) DO (
SET "line=%%a"
CALL SET "line=%%line:\=/%%"
CALL SET "line=replacement text%%line:~59%%"
FOR /f "tokens=1*delims==" %%x IN ('set line') DO ECHO %%y
)
)>newfile.txt
GOTO :EOF
where Q21495128.txt was my test source file worked for me.

How to remove special characters from string using batch

I have very little knowledge in batch programming. I want to remove special characters from string Suppose If String= " How:to,convert special characters" wants to convert into this " How-to-convert-special-characters " ( how to do if there are multiple characters like ,; : ) Kindly help! Thanks
#ECHO OFF
SETLOCAL
SET String=" How:to,convert special characters how to do if there are multiple characters like ,; : "
SET string1=%string:,=comma%
SET string2=%string:;=semicolon%
SET string3=%string::=fullcolon%
SET string4=%string3:;=SEMICOLON%
SET string4=%string4:,=COMMA%
SET string
The simple formula is SET varname2=%varname1:stringtoreplace=replacement%
It does have limits though. You would run into problems with certain characters like ^="% amongst others.
You may use the substring replacement to change individual characters, as Peter Wright suggested, but this method preserve multiple characters, so a further change of multiple dashes by just one would be needed. If your objective is to separate words with just one dash eliminating multiple separation characters (even multiple spaces), then you may use a different method.
The FOR Batch command process words separated by spaces (single or multiple):
for %%a in (one two three four ) do echo %%a
one
two
three
four
You may use Delayed Expansion to collect the words processed by FOR command into a single variable (for details, type set /? and look for "delayed expansion"):
setlocal EnableDelayedExpansion
set string=
for %%a in ( one two three four ) do set string=!string! %%a
echo "%string%"
" one two three four"
The standard separators for FOR words may be commas, semicolons and equal-signs, besides spaces (single or multiple):
for %%a in (one,two= ;; ,, three ===;;;,,, four ) do ...
This way, you may directly use a FOR command to eliminate multiple spaces, commas, semicolons (and equal-signs):
for %%a in (%string%) do ...
If you want to also eliminate one character more (like colon), you may change that character by space (or comma, semicolon or equal-sign) in the same FOR command:
for %%a in (%string::=;%) do
If you want to eliminate more characters, you may first change all of them in the string and then use FOR.
The Batch file below read a string and change multiple spaces, commas, semicolons, (equal-signs); colons and points, and insert a single dash between words:
#echo off
setlocal EnableDelayedExpansion
set /P input=Enter a string:
set input=%input:.=,%
set output=
for %%a in (%input::=;%) do set output=!output!%%a-
rem Eliminate the last dash:
set output=%output:~0,-1%
echo Output: "%output%"
You must note that not all special characters can be processed this way.

Resources