String Handling in BAT batch (string interception) _dos/bat

Source: Internet
Author: User
Tags current time extend goto strlen truncated

These features are explained below.

1, intercept the string

Intercepting a string can be said to be one of the most common functions of string processing, one or more characters that can be used to intercept a particular position in a string. Illustrate its basic functions:

Copy Code code as follows:

@echo off
Set ifo=abcdefghijklmnopqrstuvwxyz0123456789
Echo Original string (ordinal number of characters of the second act):
Echo%ifo%
Echo 123456789012345678901234567890123456
Echo intercepts the first 5 characters:
Echo%ifo:~0,5%
Echo intercepts the last 5 characters:
Echo%ifo:~-5%
Echo intercepts the first to the penultimate 6th character:
Echo%ifo:~0,-5%
Echo starts with the 4th character and intercepts 5 characters:
Echo%ifo:~3,5%
Echo begins with the last 14th character and intercepts 5 characters:
Echo%ifo:~-14,5%
Pause

Of course, the above example only shows the basic function of string processing, and it doesn't see what the use of string processing is. The following example deals with time.

Copy Code code as follows:

@echo off
Echo Current time is:%time% is%time:~0,2% point%time:~3,2% minute%time:~6,2% seconds%time:~9,2%
Pause

2. Replacement string
replaces a string that replaces a specific character or string in a string with the given string. Illustrate its function:

Copy Code code as follows:

@echo off
Set aa= great China! I'm proud of you!
Before echo Replacement:%aa%
echo Replacement:%aa: China =% of the People's Republic
echo AA =%aa%
Set "AA=%AA: China =% PRC"
echo AA =%aa%
Pause

For the example above, a comparison of two echo AA =%aa% can be found, if you want to modify the contents of the variable AA, you need to modify the result "%AA: China =% of the People's Republic" assigned to the variable AA. The string interception above also has the same characteristics.

3. String merging

In fact, merging strings is a combination of two strings. An example is provided:

Copy Code code as follows:

@echo off
Set aa= great China!
Set Bb= I'm proud of you!
Echo%aa%%bb%
Echo aa=%aa%
Echo bb=%bb%
Set "aa=%aa%%bb%"
Echo aa=%aa%
Pause

Similarly, if you want to change the contents of a variable AA, you need to assign the merged result "%aa%%bb%" to the variable AA.

4. Expansion string

The term "expansion" comes from Microsoft's own translation, which means that the string that represents the path to the file is handled in a special way, with the following features listed below:
=========================================
~i-Remove any quotes ("), expand%I
%~fi-Will%I Extend to a fully qualified path name
%~di-Will%I only Expand to a drive letter
%~PI-Will%I only Extend to a path
%~ni-Will%I only Extend to a filename
%~xi-Will%I only Extended to a file name extension
%~si-The extended path contains only short names
%~ai-Will%I File attributes extended to files
%~ti-Will%I Date/time of expansion to file
%~zi-Will%I Expand to the size of the file
~ $PATH: I-Find directories listed in PATH environment variables, and%I Expand
To the first fully qualified name found. If the environment variable name
is not defined, or the file is not found, the key combination expands to the
Empty string
You can combine modifiers to get multiple results:
%~DPI-Will%I only Extend to a drive letter and path
%~nxi-Will%I only extended to a filename and extension
%~FSI-Will%I only Extended to a full pathname with a short name
%~DP$PATH:I-finds the directory listed in the PATH environment variable, and%I Expand
To the first drive letter and path found.
%~ftzai-Will%I DIR extended to a similar output line
=========================================
The above refers to the for/? Help information. I represent the variable i, but it should be noted that not all variables can be expanded, there are two conditions: 1, the string represents a file path, 2, the variable to be represented by%x, X is preferable to a-Z-A-A, 0-9 of the total 62 characters in any one. An example is provided:

Copy Code code as follows:

@echo off
Echo is running this batch:
echo Full path:%0
echo Remove Quote:%~0
echo Partition:%~d0
Echo Path:%~p0
echo FileName:%~n0
echo Extension:%~x0
Echo File properties:%~a0
echo Modification Time:%~t0
echo File Size:%~z0
Pause

Where%0 is the parameter in the batch that represents the full path of the currently running batch. Similarly, there are%1-%9, which represent the 第1-9个 parameters that are passed on to each other. Examples are as follows:

Copy Code code as follows:

@echo off
Set AA=C:\WINDOWS\PPP\A.BTX
Call:d EAL AAA%aa% "C C" ddd Eee
Pause>nul
Exit
:d EAL
echo%%0 =%0
echo%%1 =%1
echo%%2 =%2
echo%%3 =%3
echo%%4 =%4
echo%%5 =%5

In which, the variable AA can not be expanded before, through the call command and the AA as a parameter passed to the child function: Deal, the AA variable to convert to the variable% 1, that is, the%x format, so that string expansion.
As for the X in%x in the form of a A-Z, you can review the for statement, the for statement inside the variable is represented by%x, so you can directly expand.

The following is another netizen's supplement: note is with C language do some contrast

First of all, batch and high-level languages are different, there is no string processing functions, such as strcat, but you can use environment variables to implement the functions of these functions.
In this paper, the method of implementation in batch processing is explained against the string processing function in C language.

First of all, the storage of strings, in C language, using character arrays or character pointers to store strings, and bat does not have these things, so rely on environment variables to store.
The statement setting the environment variable is a set statement, which is not described in detail in this article, reference to the set/? statement.

1, the strcpy function in C, copies a string to another character pointer or character array, overwriting the original string.

Call method in C language: strcpy (target string, source string)

How to implement in batch processing:

Set Target string =% source string%

Example:

Copy Code code as follows:

@echo off
:: Turn off screen echo (optional)
Set Str1=this is old string
:: Set the string stored in the STR1, note that there is no double quotes, this is different from the C language!
Set Str2=this is new string
:: Sets the string stored in the STR2
Echo performs a string copy before:
Echo str1=%str1%
Echo str2=%str2%
:: Output the original string first
Set str1=%str2%
:: String Copy
After Echo performs a string copy:
Echo str1=%str1%
Echo str2=%str2%
:: Output string after execution of string copy
echo output complete, press any key to exit &&pause>nul&&exit
:: Output information, ending the batch when the user presses any key.

2, the Strcat function in C to connect a string to the end of another character pointer or character array.

Call method in C language: strcat (target string, source string)

How to implement in batch processing:

Set target string =% target string%% of source string

Example:

Copy Code code as follows:

@echo off
Set Str1=this is string1
Set Str2=this is string2
:: Sets the string stored in str1 and str2
Echo Connection string before:
Echo str1=%str1%
Echo str2=%str2%
:: Output the original string first
Set str1=%str1%%str2%
:: String concatenation
echo Connection string after:
Echo str1=%str1%
Echo str2=%str2%
:: Output two strings after string connection execution
echo output complete, press any key to exit &&pause>nul&&exit

3, string interception, C does not have this function, but can be implemented through the statement, no longer introduced, directly said batch processing.

Set Target string =% source string: ~ Start value, intercept length%

Note that the starting value starts at 0!
The interception length is optional, and if the comma and intercept length are omitted, it will be truncated from the starting value to the end of the string.

Example:

Copy Code code as follows:

@echo off
Set Str1=this is string1
:: Sets the string stored in the STR1
Set str2=%str1:~8,6%
Set str3=%str1:~0,4%
Set str4=%str1:~5%
:: String interception
Echo Original string:
Echo str1=%str1%
echo intercepts the resulting string:
Echo str2=%str2%
Echo str3=%str3%
Echo str4=%str4%
:: Output Execution results
echo output complete, press any key to exit &&pause>nul&&exit

4, the Strlen function in C, gets the length of the string.

Call method in C language: strlen (String)

The implementation method in batch processing is to use goto and tag to form a looping structure, to continuously shorten the string by 1 characters, and to record the truncated number of variables, until the string becomes empty.

Example:

Copy Code code as follows:

@echo off
Set Str1=this is a test string
Set Str2=hello World
:: Set two strings
Set str=%str1%
:: Copy str1 to Str
: Next1
:: Tags, for goto jump
:: Note the difference from the comment statement, which starts with a two colon, and the label is a colon
If not "%str%" = "" (
:: To determine if STR is not an empty string, and if not, execute the statement below
set/a num+=1
:: arithmetic operation, which increases the value of NUM by 1, equivalent to num++ or ++num statements
Set "str=%str:~1%"
:: intercepting string, assigning itself
Goto NEXT1
:: Jump to Next1 label
:: Here use Goto and tag to form a cyclic structure
)
:: When the above loop structure finishes executing, the following statement is executed
Echo str1=%str1%
The length of the Echo str1 is:%num%
:: Output Results
Set num=0
:: Use the environment variable num 0 To start the next operation.
Set str=%str2%
:: Copy str2 to Str
: next2
:: Defining a new label
:: Note that you cannot have the same name as an existing label, otherwise there will be an error!
If not "%str%" = "" (
set/a num+=1
Set "str=%str:~1%"
Goto NEXT2
)
:: Similar to previous loop, no longer introduced
Echo str2=%str2%
The length of the Echo str2 is:%num%
:: Output Results
echo output complete, press any key to exit &&pause>nul&&exit

5, C, the STRCHR function, in a string to find the first occurrence of a character position, when found to return to the location, can not find the return 0 value.

Batch processing of ideas: constantly truncated short string, and take truncated after the first character string, and the required character comparison, if the same on the use of Goto statement out of the loop, output results, if not the same characters, execution to the end of the output of 0 value.

Example:

Copy Code code as follows:

@echo off
Setlocal enabledelayedexpansion
:: Enable command extensions, join setlocal/? command
Set Str1=this is a test string
Set ch1=t
:: Note that the case is case-sensitive!
Set str=%str1%
:: Copying a string to truncate without affecting the source string
: Next
If not "%str%" = "" (
set/a num+=1
If "!str:~0,1!" = = "%ch1%" goto Last
:: Compare the first character to the required character and jump out of the loop if it is
Set "str=%str:~1%"
Goto Next
)
set/a num=0
:: When characters are not found, Num is zero
: Last
The first occurrence of the echo character '%ch1% ' in the string "%str1%" is%num%
echo output complete, press any key to exit &&pause>nul&&exit

Reference:
Finally a few questions, see how we learn!
(1) How to realize the function of strstr function in C language?
Tip: The function of the STRSTR function is to find the string 2 in string 1, return the first occurrence of string 2 when found, or return a 0 value. The difference with STRCHR is that the second argument is a string, not a character.

(2) How do I build a while loop with batch processing?
Tip: The while loop generally has the following format:
while (expression)
{
Circulation body
[Break|continue;]
Circulation body
}
Where the loop body is 0 or more statements, the break is used to jump out of the loop, and continue is used to directly determine the expression and decide whether to go to the next loop.
General Order of execution: first, the expression is judged, if set up then enter the loop, the loop body after the completion of the evaluation of the value of the expression, decide whether to cycle again.

(3) How to use batch processing to build Do-while cycle?
Tip: The general format of the Do-while cycle is:
Todo
{
Circulation body
[Break|continue;]
Circulation body
}while (expression);
The interpretation of individual statements references the while loop.
General Order of execution: first into the loop, the loop body after the completion of the evaluation of the expression value, the expression is set up again into the loop.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.