当前位置:网站首页>[batch dos-cmd command - summary and summary] - jump, cycle, condition commands (goto, errorlevel, if, for [read, segment, extract string]), CMD command error summary, CMD error
[batch dos-cmd command - summary and summary] - jump, cycle, condition commands (goto, errorlevel, if, for [read, segment, extract string]), CMD command error summary, CMD error
2022-07-07 00:57:00 【dssgresadfsrgre】
One 、 Abstract of this article
This paper mainly studies the implementation of code branching and reuse .
Branching execution refers to the code that determines the next step according to the actual execution result in the middle of the process , Jump code line number ; Branch execution is roughly divided into jump execution 、 Condition judgment execution ; therefore , Branching execution basically only executes part of the code , Part of the code is not executed .
Implementation of code reuse , On the one hand, it depends on program calls ( For details, please refer to what I wrote CMD Command implementation program call a text ), On the other hand, based on circular commands .
Two 、 Jump command ——goto
Print goto Command help information .
We can see that there is only one parameter of this command label.
Specific application methods —— stay goto Put a line below the command , It begins with an English colon followed by “ Branch identifier ”, And then again goto Add “ Branch identifier ” Of label Parameters .
Application examples on , some bat The code of the file is as follows :
chcp 65001
@echo off
echo Little adult , Are you tired of playing ?
goto part1
echo I'm tired , I don't want to talk , Please turn to part1 sir
:part1
echo ......
echo ......
echo ......
echo Ten minutes later ...
echo Now press any key to continue playing
pause
After execution , The result is shown in the figure ,【echo I'm tired , I don't want to talk , Please turn to part1 sir 】 Not implemented .
Be careful : about goto The label after the command , It can be done without colon (goto part1), You can also add a colon (goto :part1), The effect is the same .
3、 ... and 、 Misjudged branch execution ——errorlevel and &&、||
3.1 Error feedback command ——errorlevel
To be precise ,errorlevel It's a variable , Not orders ; So printing it directly will make an error .
What is used for printing ? Certainly echo Brother , Carry out orders 【echo %errorlevel%】.
If the result is 0, Then there is no mistake ; The larger the error code, the stronger the severity of the error .
The value of the error code cannot be greater than 0 Still small , That is, it cannot be negative .
3.2 Error judgment operator ——&&、||
In the column 【Cmd-Dos】 in , There is an article dedicated to cmd dos All operators in the command ( Function symbol ) It is summarized .
【 The batch DOS-CMD command - Summary and summary 】-Cmd Common operators in Windows
As mentioned above && and || Both have the function of judgment , But it's essentially the same as if There are still differences in command statements , Because they can only be used to judge whether the implementation is smooth ( For example, whether the specified string is found in the target text file ), Or command syntax error , The judgment index is to look at the variables after the execution of the previous command errorlevel Value , If the value is 0 It means smooth , If not for 0 Even if it's wrong .
As shown in the figure below , although del The command to delete a nonexistent file is not an error , But renaming a nonexistent file is a mistake .
3.2.1 Cmd The general error of the command results in errorlevel change
(1) Command syntax class error
error A: Not an internal or external command , It's not a runnable program
for example , Before learning this article 3.2.2 Before the bar , I don't know that many conditional judgment keywords can only be used in if Use , So execute the command 【3 GTR 5 && echo 3 Greater than 5 || echo 3 Less than or equal to 5】 An error has occurred .
error B: Invalid switch
When will an invalid switch be reported ? When there is a backslash in the relative path 【\】 when , The command statements used only support parsing forward slashes 【\】 when , It will report an invalid switch .
such as dir command , Only backslash characters can be used when specifying relative paths 【\】, Once you use the forward slash 【/】, It will report an invalid switch .
In another case, an invalid switch will also be reported . That is, when you print the help information of a command , Question marks use Chinese characters . For example, execute command 【dir /?】 .
error C: Incorrect parameter format
When there is a backslash in the absolute path 【\】 when , The command statements used only support parsing forward slashes 【\】 when , An error will be reported, and the parameter format is incorrect .
(2) There is no class 、 Class error not found
Copying 、 Move 、 Change of name 、 Inquire about 、 Display or on a file ( clip ) When doing other operations , We need to guarantee this document ( clip ) Exist honestly , Otherwise, an error will occur .
Copy command copy, When the file to be copied does not exist , Report errors .
Mobile command move, When the mobile destination cannot be found , You will also report mistakes. .
Rename command ren, When the file to be renamed does not exist , Report errors .
Commands for querying directory composition or specifying file location dir, An error will be reported when the file cannot be found , In addition, it is not shown in the figure “ Specified a nonexistent directory ”
Commands for querying strings find、findstr, The target string cannot be found in the search source , You're going to report a mistake .
(3) Coding class error
When cmd Use default encoding (ANSI code ), The characters in the text file are utf8 When coding ;
Extract it from it to cmd An error will be reported in the window —— Write error ,
take ANSI Code modified to utf8 code .
(4) It seems that something will go wrong, but it's actually right
reverse A: Delete nonexistent files ( clip ) you 're right
3.2.2 Reverse cognition - There is no substitute for if Many functions of command statements
(1)if Can judge whether it exists , however &&、|| You can't
if [not] exist <filename> <command> [else <expression>]
(2)if Can judge whether two strings are the same , however &&、|| You can't
if [not] <string1>==<string2> <command> [else <expression>]
(3)if Can compare the size between two numbers ( For example, relational operators EQU Is equal to ), however &&、|| You can't .
if [/i] <string1> <compareop> <string2> <command> [else <expression>]
(4)if Can judge whether a variable is defined , however &&、|| You can't
if defined <variable> <command> [else <expression>]
(5)if Can judge whether the error code is greater than or equal to a specific value , however &&、|| You can't ;&&、|| You can only judge whether the error code is equal to 0.
if [not] ERRORLEVEL <number> <command> [else <expression>]
(6)if Be able to judge cmd Whether the version number is greater than or equal to a specific value , however &&、|| You can't
if cmdextversion <number> <command> [else <expression>]
The six functions above , I will explain it in the fifth part of this article .
Four 、 Loop traversal command for Explanation
Reference source : Batch command ——for - kaizen - Blog Garden
4.1 Print for Command help information
D:\D-desktop>for /?
Execute a specific command for each file in a set of files .
FOR %variable IN (set) DO command [command-parameters]
%variable Specify a single letter replaceable parameter .
(set) Specify a file or group of files . You can use wildcards .
command Specify the command to execute for each file .
command-parameters
Specify parameters or command line switches for specific commands .
Use... In batch programs FOR On command , To specify a variable, use %%variable
And don't use %variable. Variable names are case sensitive , therefore %i differ %I.
If command extension is enabled , Will support the following FOR Other formats of commands :
FOR /D %variable IN (set) DO command [command-parameters]
If the set contains wildcards , The specified name matches the directory name , Without matching the file name .
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Check to [drive:]path Directory tree as root , Point to in each directory FOR sentence .
If in /R No directory specification specified after , Use the current directory . If the set is only a single point (.) character ,
Then enumerate the tree .
FOR /L %variable IN (start,step,end) DO command [command-parameters]
This set represents a sequence of numbers in incremental form from start to end . therefore ,(1,1,5) The sequence will be generated
1 2 3 4 5,(5,-1,1) The sequence will be generated (5 4 3 2 1)
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
perhaps , If there is usebackq Options :
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
fileset For one or more filenames . Continue to fileset Before the next file in ,
Every file is opened 、 Read and process . Processing includes reading files , Split it into lines of text ,
Then parse each line into zero or more symbols . Then call... With the value of the symbolic string variable that has been found For loop .
By default ,/F Through the first space separated in each line of each file . Skip the blank line .
You can specify an optional "options" Parameter instead of the default parse operation . The quoted string includes a
Or more keywords that specify different parsing options . These keywords are :
eol=c - The end of a line comment character ( Just one )
skip=n - The number of lines ignored at the beginning of a file .
delims=xxx - The set of separators . This replaces spaces and tabs
Default separator set .
tokens=x,y,m-n - It refers to which symbol of each line is passed to each iteration
Of for In itself . This results in the allocation of extra variable names .m-n
The format is a range . adopt nth Symbol assignment mth. If
The asterisk of the last character in the symbol string ,
Then the extra variables will be resolved after the last symbol
Assign and accept reserved text for lines .
usebackq - Specifies that the new syntax is already used in the following case :
Execute a quoted string as a command and a single
Quote characters are text string commands and are allowed in file-set
Use double quotation marks to expand the file name .
Some examples may help :
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Can analyze myfile.txt Each line in , Ignore lines that start with semicolons , take
The second and third symbols in each line are passed to for The body of the function , Use commas and / or
Space separator . Please note that , this for Statement reference of function body %i Come on
Get the second symbol , quote %j To get the third symbol , quote %k
To get all the remaining symbols after the third symbol . For files with spaces
name , You need to enclose the file name in double quotation marks . In order to make
Use double quotes , You also need to use usebackq Options , otherwise , Double quotes will
It is understood that it is used to define a string to be analyzed .
%i stay for The statement explicitly declares ,%j and %k It's through
tokens= Options are implicitly declared . Can pass tokens= a line
Specify a maximum of 26 Symbols , Just don't try to declare a higher than letter "z" or
"Z" The variable of . please remember ,FOR Variables are single letters 、 There are case and global variables ;
and , Cannot use more than at the same time 52 individual .
You can also use FOR /F Analytical logic , The method is ,
Use single quotation marks to enclose the text between parentheses file-set Cover up . such , This character
The string is parsed as a single input line in a file .
Last , It can be used FOR /F Command to analyze the output of the command . The method is , take
Between brackets file-set Becomes an inverted string . The string will
As a command line , Pass to a child CMD.EXE, Its output will be captured
In the memory , And analyzed as a document . As the following example shows :
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
Enumerates the names of environment variables in the current environment .
in addition ,FOR Substitution of variable references has been enhanced . You can now use the following
Option grammar :
%~I - Remove any quotes ("), Expand %I
%~fI - take %I Expand to a fully qualified pathname
%~dI - Only will %I Extend to a drive letter
%~pI - Only will %I Extend to a path
%~nI - Only will %I Extend to a file name
%~xI - Only will %I Extend to a file extension
%~sI - The extended path contains only the short name
%~aI - take %I File properties extended to files
%~tI - take %I Date extended to file / Time
%~zI - take %I Expand to file size
%~$PATH:I - Find the directory listed in the path environment variable , And will %I Expand
To the first fully qualified name found . If the environment variable name
Undefined , Or no files found , This key combination extends to
An empty string
You can combine modifiers to get multiple results :
%~dpI - Only will %I Expand to a drive letter and path
%~nxI - Only will %I Extend to a file name and extension
%~fsI - Only will %I Expand to a full pathname with a short name
%~dp$PATH:I - Search directories listed in path environment variables , And will %I Expand
To the first drive letter and path found .
%~ftzaI - take %I Extended to similar output lines DIR
In the example above ,%I and PATH It can be replaced by other valid values .%~ grammar
Use a valid FOR Variable name termination . Select something similar to %I Upper case variable name of
It's easier to read , And avoid confusion with case insensitive key combinations .
In the following 3.1.2 to 3.1.4 I will help you summarize the basic syntax rules of each field , If you can't understand it at once , No problem , You can go first 3.1.5 Let's look at the application cases of each parameter later .
4.2 variable The basic grammatical rules of
(1) Can only be 26 One of the letters , Of course 10 One number is ok , But easy and batch form parameters %0-%9 Conflict , It's recommended to use 26 One of the letters .
(2) Case sensitive , That is to say %i and %I It's different .
(3) stay cmd Use... In the window , Variable names must be in single % quote ( namely :%variable); Use in batch scripts , Variable names must be double % quote ( namely :%%variable).
(4) When the parameter is set to /f when , If variable Set to i, So the back parameters Must be set to i、j、k、l..., That is, if you need to command Enter multiple parameters, that parameters Variables can only be sequenced from variable Start naming .
4.3 set The basic grammatical rules of
(1) parentheses () Don't save , That is, there is no room for negotiation , Must be written as (set) In the form of .
(2) When no parameters are set ( That is, no /l、/d、/f、/r Any one ) when , One set It can include multiple elements , Available spaces between elements 、 Jumping lattice 、 comma 、 Separated by semicolons or equal signs .
(3) When the parameter is set to /l when ,set There can only be 3 Elements , Elements can only be separated by commas , Namely start( Starting value )、step( Step value )、end( Maximum , It can be equal to but not larger than this ).
(4) When the parameter is set to /d when ,
4.4 command and parameter Grammatical rules
In the help message command-parameters Corresponding to this article parameters.
(1) Under normal circumstances parameter only one , and variable Exactly the same .
(2) When for The command parameters are /f when ,parameters There may be more than one , If variable Set to i, So the back parameters Must be set to i、j、k、l..., That is, if you need to command Enter multiple parameters, that parameters Variables can only depend on 26 The order of letters is from variable Start naming .
(3)
4.5 Without parameters ,set You must manually specify multiple
Without parameters ,for The syntax rules of the command are as follows .
stay cmd Use format in window .
FOR %variable IN (set) DO command [command-parameters]
Use formats in batch scripts .
FOR %%variable IN (set) DO command [command-parameters]
for instance , Suppose we want to output a series of numbers continuously .
Create a new one bat file , The code is as follows :
@echo off
for %%i in (1 2 3 4 5) do @echo %%i
pause>nul
The output is as follows
4.6 Parameter is /l when , Just specify the first 、 step 、 And tail
When the parameter is /l when ,for The syntax rules of the command are as follows .
stay cmd Use format in window .
for /l %variable in (start,step,end) do command [command-parameters]
Use formats in batch scripts .
for /l %%variable in (start,step,end) do command [command-parameters]
Yes set(start,step,end) Detailed limitations :
[1] start Refers to the starting value ;step Finger step spacing ;end Refers to the end value .
[2] start、step and end Can only take integer ( Both positive and negative ).
[3] Step spacing step The value of cannot be 0.
[4] Step spacing step When the value of is a positive integer , Termination value end Cannot be less than the initial value start.
[5] Step spacing step When the value of is a negative integer , Termination value end Cannot be greater than the initial value start.
for instance , Suppose we want to output 【2,4,6,8,10,12,14,16,18,20 ,22,24,26,28,30】, Because it's too long to use this article 3.1.5 Section method .
We can build a new bat file , The code is as follows .
@echo off
for /l %%i in (2,2,30) do echo %%i
pause>nul
The output is as follows .
When you understand for /l After the specific functions of , Will you think of something similar to it goto Loop statements ? Seems to be ,for /l and goto Circular statements can be replaced with each other ?
generally speaking ,for /l The statement can be replaced by goto loop , however ,goto A cycle may not be for /l Replace... With .
The specific reason , Please think carefully .
Just provide a concise answer to a question that everyone is very concerned about , That's it : When should I use it for /l Count cycle , And when should I use goto condition loop ?
The answer is very simple :
When the number of cycles is determined , The preferred for /l sentence , You can also use goto Statement but not recommended ;
When the number of cycles is uncertain , use goto Statement will be the only choice , because , At this time, we need to use if And other conditional statements to determine when to end goto Jump .
4.7 Parameter is /d when , The file ( clip ) To operate
When for The parameters of the command are /d when , For files at the specified directory level ( clip ) To operate , The rules of grammar are as follows .
stay cmd Window .
for /d %variable in (set) do command [command-parameters]
stay bat In the script file .
for /d %%variable in (set) do command [command-parameters]
(1) In this case set Support for wildcards 【*】 and 【?】, When wildcards are used, the folder under the specified drive and path will be searched .
Suppose we want to be in music Search under the folder to “test” How many folders are there at the beginning .
Carry out orders 【tree /f】, You can see music There are 3 A folder ,test1 There is also a subfolder under test4. There are also some hidden folders 、 Hidden files are not displayed , But you should know that their names bear hide keyword .
bat The document code is as follows .
@echo off
for /d %%i in (C:\Users\Administrator\Downloads\Music\test*) do echo %%i
pause>nul
The results are as follows , Does not include test1 Under the test5、test2 Under the test3, This is because only the first level folders are searched ; In addition, it is also related to for /r There is no way to search Hide Folder .
(2) When wildcards are not used , The usage is the same as that without any parameters .
for example , Change the following code .
@echo off
for %%i in (1 2 3 4 5) do @echo %%i
pause>nul
Add a parameter /d, It is also reasonable !
@echo off
for /d %%i in (1 2 3 4 5) do @echo %%i
pause>nul
4.8 When the parameter is /r when , Do recursive traversal
When for The parameters of the command are /r when , It will recursively traverse the files in the specified path and its sub directories ( clip ), The basic rules of grammar are as follows .
stay cmd Window .
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
stay bat Script .
FOR /R [[drive:]path] %%variable IN (set) DO command [command-parameters]
[[drive:]path] Is very simple to use . If you don't specify , It defaults to the current directory . This path parameter is the starting point of recursive traversal , The path parameters obtained will only be deeper , Not shallower .
(set) Worth explaining , There are two situations .
(1) When set Without wildcards , Directly recursively traverse the specified directory and all its sub directories , Then connect the back of these directory paths with set Connect the string elements in to get a new path .
Test folder and its files , Structure hierarchy and above parameters /d Of the (1) As described in part .
The test code is as follows .
@echo off
for /r C:\Users\Administrator\Downloads\Music %%i in (a b c) do echo %%i
pause>nul
The test results are as follows , I didn't expect to inquire Hide Folder !
(2) When set With wildcards , Recursively traverse to get all file paths under the specified directory , Only the file name matches set The path of grammar rules in .
The same test environment is the same (1).
The test code is as follows .
@echo off
for /r C:\Users\Administrator\Downloads\Music %%i in (test*) do echo %%i
pause>nul
The results are as follows , No query Hidden files .
4.9 Parameters /d And parameters /r Combine —— Recursively traverse each child folder
stay for In command ,( Looks like ) Only parameters /r And parameters /d Can be used in combination with , The combination effect is actually in the parameter /d The expansion on , So that it can recursively traverse the directories that meet the requirements in each sub folder .
Or to (1) Based on the example in , The following command can search Music Under the folder ( Include child folders ) All with test The starting list .
@echo off
for /d /r C:\Users\Administrator\Downloads\Music %%i in (test*) do echo %%i
pause>nul
The command above , Be careful /d stay /r front , Otherwise, double clicking execution will flash back .
/r The following path parameters , In fact, it represents the search “ The starting position ”, Essentially, and parameters /r Used in combination with , It means recursively traversing the target path and the files under its sub directories ( clip ).
in hinder (set), Represents the matching rule , Essentially, and parameters /d Used in combination with , When there are wildcards, it means that the folder matching the rules .
combined , Just traverse the path 【C:\Users\Administrator\Downloads\Music】 in ( Including sub directories ) Conform to the rules 【test*】 Folder .
Double click to execute as follows . Perfectly in line with expectations !
These two parameters are combined , It makes up for using only parameters /d The defect of not recursively traversing child directories , It also avoids using only parameters /r If you use wildcards, you can't match the directory , It's simply the complementarity of advantages and disadvantages 、 A perfect match !
4.10 Parameters /f—— Born for parsing text
for If the parameter of the command is /f, The function becomes parsing text , It needs to be used with other commands that can generate text 、 Or point to a text file 、 Or enter a string text directly . The basic rules of grammar are as follows .
The following is in cmd Syntax example of window direct execution , stay bat The syntax examples in the script are simplified accordingly 、 It's done .
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
We can see , Generally speaking, there are 3 Usage , The first is a collection of text files ( No border wrap )、 The second is a string text set ( Need double quotation marks to wrap )、 The third is the command that can output text ( Need single quotation marks to wrap ).
In fact this 3 Kind of , Only the way of entering text is different , The existence form of the final text can be the same , So don't explain it as a key point .
We focus on fields ["options"], Field [command-parameters] And field (set) As a secondary point, the boundary character of .
Let's intercept the relevant help information , Let's focus on this ; There is a small mistake that needs to be found .
eol=c - The end of a line comment character ( Just one )
skip=n - The number of lines ignored at the beginning of a file .
delims=xxx - The set of separators . This replaces spaces and tabs
Default separator set .
tokens=x,y,m-n - It refers to which symbol of each line is passed to each iteration
Of for In itself . This results in the allocation of extra variable names .m-n
The format is a range . adopt nth Symbol assignment mth. If
The asterisk of the last character in the symbol string ,
Then the extra variables will be resolved after the last symbol
Assign and accept reserved text for lines .
usebackq - Specifies that the new syntax is already used in the following case :
Execute a quoted string as a command and a single
Quote characters are text string commands and are allowed in file-set
Use double quotation marks to expand the file name .
eol Parameters and skip Parameters are used to specify the lines to be omitted .
(1)eol The help information of the parameter is “ The line comment character is at the end of the sentence ”, This is wrong , It should be the beginning of the sentence .
eol The value of the parameter c It's a symbol , The default line comment character is a semicolon 【;】, So if you don't want to activate line comments , The parameters are written as 【eol=】( Do not give eol assignment ), If you want to change the line comment character ( Like exclamation marks ), The parameters are written as 【eol=!】.
“ Just one ” It means , every last for The command can only specify one line comment character , Or 【;】、 Or 【!】.
(2)skip The value of the parameter n Determines how many lines at the beginning will be omitted , Suppose the following set Only 3 Line text , and skip=2, And the last line of text is not “ Line notes ”, Then only one line of text will be output .
(3)delims Parameters are used to specify how the text of each line should be cut and divided , If it is not specified, it defaults to space or tab ( tabs ). If you don't want to do any cutting , You need to assign a null value to the parameter , That is to say 【delims=】. If you want to change the cutter , You can assign other values , For example, comma 【,】, Then add 【delims=,】.
(4)tokens Parameter is used to select the cut segment of each line and send it to variable. If you don't specify , By default, only the first segment is selected and passed to variable. Help information is called “ Symbol ”, In fact, the translation is not accurate enough , Translated into “ fragment ” Just right .
for Commands are executed in behavioral units , Not a fragment .
Allow multiple clips to be selected , The index numbers are separated by commas , for example tokens=1,3,4. Selecting multiple clips does not mean %variable It needs to be written in multiple , Just write a first variable , such as %i; But the back parameters According to tokens Set the same number of selected clips . First parameter naming and variable identical , Only the following parameters must be named according to 26 In alphabetical order . If the first parameter is %a, Then the following parameters must be %b、%c、%d、%e......
If you need to select multiple clips consecutively ( Does not mean that it is entered into a variable), Use a dash between the first index number and the last index number , for example tokens=2-4, You can segment 2、3、4 Pass it to three parameter.
If you need to fuse the cut fragments into one fragment , Pass this clip to a parameter, You can use the plum blossom symbol at the bottom , For example, if there are 5 A fragment , Add parameter 【tokens=1-3,*】, You can segment 4 And clips 5 Merge together ( It won't be delims Specify Division ) To the last parameter.
Unfortunately , You can only fuse unspecified clips from right to left , Stop fusing until the next segment is assigned . That is to say, suppose that the fragments are 7 individual , Parameter is 【tokens=1-2,4-5,*】, The last segment 3 Will be discarded , Only fragments can be fused 6 And clips 7.
tokens The index numbers in do not have to be placed in ascending order from left to right , It can also be in descending order , But in the end parameter The received clip does not affect . for example 【tokens=1-2,4-5,*】 Actually sum 【tokens=4-5,1-2,*】 As like as two peas ,【tokens=2-3,1,*】 Actually sum 【tokens=1,2-3,*】 As like as two peas .
(5) When set Is a collection of text files and the file name contains spaces , In order to avoid the problem of path spaces and special symbols ( For example, including & when ), Use the traditional way of adding double quotation marks to solve , Will be with for command /f Syntax rules of parameters conflict ( Because double quotation marks belong to the string text set , The file name will be treated as an ordinary string , How can it be so ).
therefore ,CMD The developer set a switch parameter usebackq, Adding this parameter turns on the fallback rule switch .
What is the backup rule ? It means another set of rules .
The original rules are as follows
Text file collection | String collection | Text generation command |
Unsigned | Double quotes "" | Single quotation marks '' |
The backup rules are as follows
Text file collection | String collection | Text generation command |
Double quotes "" | Single quotation marks '' | The back quotation marks ``( Same key as wave symbol ) |
After activating fallback rules , Then use double quotation marks to wrap the file path with spaces or special symbols , Would not be “ Misidentification ” Into a normal string !
The following is a case study 1,set It's a text file .
stay D Disk path 【D:\Program Files\python】 So let's make a new one txt file ( The comma is Chinese , So in the following code delims Also give Chinese commas ), The contents are as follows .
Create a bat Script files , The code is as follows
@echo off
chcp 65001
for /f "usebackq eol=! skip=2 delims=, tokens=1-2" %%i in ("D:\Program Files\python\tool.txt") do echo %%i+%%j
pause>nul
Double click execute , The results are as follows
Next, we will explain why it is this result !
First , because 【skip=2】, So the first two lines are directly ignored .
secondly , because 【eol=!】, So there are a few lines with semicolons , But not commented ( Ignore ) fall .
also , because 【delims=,】, This comma is a Chinese comma , So it involves separating the upper and lower sentences of poetry with Chinese commas , The delimiters are replaced with a plus sign .
in addition , Because the file name path involves spaces , So we need to add the backup rule switch 【usebackq】.
Last , because 【tokens=1-2】, Only the first two clips are preserved , So Su Shi's love words in the last line “ Ten years of life and death ...” The last sentence of “ Forget yourself ” Ignored .
The following is a case study 2,set Is a text generation command .
hypothesis F There are a lot of folders in the software directory under the disk that need to be suffixed .
We can create a new one in any directory bat Script , The code is as follows .
@echo off
chcp 65001
for /f "delims=" %%i in ('dir /b /a:d F:\ Software ') do ren "F:\ Software \%%i" "%%i_ Welcome to Chongqing University "
pause>nul
The results are as follows .
Next, we will explain why it is this result !
First , We need to understand the order 【dir /b /a:d F:\ Software 】 What is the output text of . As shown in the figure below , Each line is a folder name .
secondly , Because there are spaces in the names of two folders , So the order 【ren】 Both the original and target names in need of double quotation marks .
Last , Because the default delimiter is a space , So you also need to add parameters 【delims=】 To cancel the segmentation of folder names with spaces .
The following is a case study 3,set Is ordinary string text .
Suppose I am an obsessive-compulsive disorder , I want to turn the space in Li Ronghao's Weibo into a Chinese comma .
I created a bat Script , The code is as follows .
chcp 65001
@echo off
for /f "tokens=1-3" %%i in (" Disappeared for a while 20000 words Finish writing ") do echo %%i,%%j,%%k
pause>nul
The results are as follows .
I hope Li Ronghao and his fans will be satisfied .
5、 ... and 、 Conditional statements ——if xx else if xx else xx
5.1 if The classical structure and typesetting skills of sentences
Reference article :bat In the script if else if Writing - Bear Man - Blog Garden
5.1.1 A row full
It's very simple for people who write code , But it is not readable for people who look at the code .
if condition1 (command1) else if condition2 (command2) else (command3)
if Part must exist ;if and else if Can be matched to exist without having to exist else part , Empathy if and else Can be matched to exist without having to exist else if part ; however else Part can only appear once ;else if In theory, some parts can be superimposed infinitely .
If you divide the conditions very carefully , Then you can add many else if part .
Unless only if part ( That is to say, there is no else if and else part ), Otherwise, you must execute the statement parts (commandx) Surround with parentheses , Otherwise, it will execute incorrectly .
@echo off
chcp 65001
if "abc"=="ABC" echo " Two strings are equal " else echo " The two strings are different "
pause
If you don't believe it, you can try copying the above code to a Bat Double click in the file to execute , In the end, it will definitely not print out any results , as if if Statements do not exist , Just do it directly Pause 了 .
If written 5.1.1 The form of such a line , Can not add parentheses ; And if it's written as 5.1.2 and 5.1.3 So many lines , You must add parentheses .
5.1.2 Multiple lines “ Brackets ” Typesetting
Yes “ A row full ” Make a new typesetting , The code body and execution effect remain unchanged .
Mainly use parentheses 【()】 Optimize the layout .
Good readability , Slightly poor compatibility .
if condition1 (
command1
) else if condition2 (
command2
) else (
command3
)
5.1.3 Multiple lines “ Brackets ”、“ Line break ” Enhanced
stay 5.1.2 Further optimize the typesetting based on , Line feed continuation is added 【^】, Greatly improve the compatibility of the code .
if condition1 (
command1
) ^
else if condition2 (
command2
) ^
else if condition3 (
command3
) ^
else (
command4
)
5.2 if The conditions that the sentence can judge are 6 Kind of
if The classic keyword of the statement 【not】 Represents the reversal of truth , And keywords 【/i】 Represents case insensitive , These two keywords can be found in the following 5.2.1-5.2.4 Used in section .
however 5.2.1 Small measure and 5.2.4 Section , It is not case sensitive .
That is, if there is a file 【paths.txt】, Do you use 【PATH.txt】 To judge, it will finally return the true value ; If there are already variables var1 Defined , So I'm judging VAR1 It will also be considered to have been defined .
5.2.1 Judge a file ( clip ) Whether there is
The rules of grammar are as follows .
if [not] exist <filename> <command> [else <expression>]
for example , I want to determine whether a file in the desktop path exists , Copy the following code to Bat Double click the file to execute .
@echo off
chcp 65001
if exist D:\D-desktop\test5\paths.txt echo " The file indicated by the path exists "
pause
give the result as follows , Of course it exists !
Some readers may wonder , Can you judge whether a folder exists ? The answer is yes .
Let's modify the code a little
@echo off
chcp 65001
if exist D:\D-desktop\test5 echo " The folder referred to by the path exists "
pause
Then double click to execute , give the result as follows ; Perfect implementation , Oh yeah !
Be careful : Case insensitive , Even if the letters in the file name or path string are written differently from the actual case , Finally, the true value of the condition will also be returned .
5.2.2 Judge whether the two strings are the same
The rules of grammar are as follows . Strings can be used without quotation marks , Added to avoid the string space problem .
if [not] <string1>==<string2> <command> [else <expression>]
Suppose I want to compare whether two string variables are the same , You can use the following code .
@echo off
chcp 65001
set var1=abc
set var2=ABC
if %var1%==%var2% echo " The two strings are the same "
pause
stay bat Execute the above code in the file , give the result as follows .
No output “ The two strings are the same ”, It shows that these two variables are actually different , Because it is case sensitive .
in addition , In order to avoid the string space problem , You can put quotation marks around the string 、 brackets 、 Curly braces , This is actually a comparison between the symbols wrapped outside and the string .
5.2.3 Can compare the size between two numbers
This usage belongs to extended usage , need cmd Open the command extension function ; Because this function is turned on by default , Therefore, it is easy to ignore the premise .
The rules of grammar are as follows . Strings can be used without quotation marks .
if [/i] <string1> <compareop> <string2> <command> [else <expression>]
If both strings are numbers , Then the comparison is the size of the two numerical quantities ; And if at least one of the two strings is not a pure number , Will be compared one by one ASCII code .
if The relational operators supported by the statement are shown in the following table .
- EQU - Equal to
- NEQ - Not equal to
- LSS - Less than
- LEQ - Less than or equal to
- GTR - Greater than
- GEQ - Greater than or equal to
stay bat Execute the following code in the file , Compare the size of two pure numeric strings .
@echo off
chcp 65001
set var1=458
set var2=456
if %var1% GTR %var2% echo " Variable var1 Greater than the variable var2"
pause
give the result as follows .
stay bat Execute the following code in the file , Compare the size of non pure numeric strings .
@echo off
chcp 65001
set var1=rth
set var2=ytb
if %var1% GTR %var2% (echo " Variable var1 Greater than the variable var2") else (echo " Variable var1 Less than variable var2")
pause
give the result as follows .
5.2.4 Can judge whether a variable is defined
This usage belongs to extended usage , need cmd Open the command extension function ; Because this function is turned on by default , Therefore, it is easy to ignore the premise .
The rules of grammar are as follows .
if defined <variable> <command> [else <expression>]
Here's an example , stay BAT Execute the following code in the file .
@echo off
chcp 65001
set var1=rth
set var2=ytb
if defined var1 (echo " Variable var1 There is ") else (echo " Variable var1 non-existent ")
if defined VAr2 (echo " Variable var2 There is ") else (echo " Variable var2 non-existent ")
pause
give the result as follows , We can see that it is not written 【%var1%】 The form with double percentile of , In addition, although it is written 【VAr2】 It also obtains the conditional truth value because it is not case sensitive .
5.2.5 Can judge whether the error code is greater than or equal to a specific value
The rules of grammar are as follows . If errorlevel The value of is greater than or equal to the following number( Numerical value range 0~255), Return the true value of the condition , And directly implement the following command command .
if [not] ERRORLEVEL <number> <command> [else <expression>]
For example, I am in bat Add search to the file tool.txt Code for , Then print the search result exit code .
@echo off
chcp 65001
dir tool.txt
echo %errorlevel%
if errorlevel 1 (echo " Greater than or equal to 1") else (echo " Less than 1")
pause
The results are as follows .
5.2.6 Be able to judge cmd Whether the version number is greater than or equal to a specific value
This usage belongs to extended usage , need cmd Open the command extension function ; Because this function is turned on by default , Therefore, it is easy to ignore the premise .
The rules of grammar are as follows . If cmdextversion The value of is greater than or equal to the following number, Return the true value of the condition , And directly implement the following command command .
if cmdextversion <number> <command> [else <expression>]
Here's an example , stay bat Execute the following code in the file .
@echo off
chcp 65001
echo %cmdextversion%
if cmdextversion 1 (echo " Greater than or equal to 1") else (echo " Less than 1%")
pause
give the result as follows , because cmd The version is 2, So I finally output “ Greater than or equal to 1”.
6、 ... and 、 Circular command ——call And %0
stay bat Directly in the script 【%0】 Or through call Command invocation %0, Will result in Bat The file is in an endless loop .
@echo off
chcp 65001
echo " The eldest brother was born "&echo " The second brother was born "&echo " Three younger sisters were born "
(
echo " The eldest brother was born "
echo " The second brother was born "
echo " Three younger sisters were born "
)
call %0
pause
You can copy the above code to bat In file , Double click to try , Will definitely continue “ Give birth to a child ” Ha ha ha .
7、 ... and 、 Circular command ——goto and if
Here is a routine .if Statement is used to determine whether the condition of continuing the loop is satisfied , Fulfill it goto Into the loop , If you are not satisfied, you will not execute goto sentence , And keep going down .
@echo off
set var=0
rem ************ The cycle begins
:continue
set /a var+=1
echo The first %var% Secondary cycle
if %var% lss 100 goto continue
rem ************ The cycle is over
echo Loop execution complete
pause
One bat In file , It can include more than one goto loop ; The method is the same as the above routine , Continue to expand in the future , As shown below, it belongs to adding two loops in one bat file .
@echo off
set var=0
rem ************ The cycle begins
:continue1
set /a var+=1
echo The first %var% Secondary cycle
if %var% lss 100 goto continue1
:continue2
set /a var+=1
echo The first %var% Secondary cycle
if %var% lss 100 goto continue2
rem ************ The cycle is over
echo Loop execution complete
pause
边栏推荐
- alexnet实验偶遇:loss nan, train acc 0.100, test acc 0.100情况
- 【批处理DOS-CMD命令-汇总和小结】-查看或修改文件属性(ATTRIB),查看、修改文件关联类型(assoc、ftype)
- 【JokerのZYNQ7020】AXI_ EMC。
- 新手如何入门学习PostgreSQL?
- [daily problem insight] prefix and -- count the number of fertile pyramids in the farm
- Notes of training courses selected by Massey school
- Part 7: STM32 serial communication programming
- 代码克隆的优缺点
- [Batch dos - cmd Command - Summary and Summary] - String search, find, Filter Commands (FIND, findstr), differentiation and Analysis of Find and findstr
- 第五篇,STM32系统定时器和通用定时器编程
猜你喜欢
Attention SLAM:一种从人类注意中学习的视觉单目SLAM
ZYNQ移植uCOSIII
Idea automatically imports and deletes package settings
Data processing of deep learning
Mujoco finite state machine and trajectory tracking
Win10 startup error, press F9 to enter how to repair?
Chapter II proxy and cookies of urllib Library
Learn to use code to generate beautiful interface documents!!!
Slam d'attention: un slam visuel monoculaire appris de l'attention humaine
threejs图片变形放大全屏动画js特效
随机推荐
集合(泛型 & List & Set & 自定义排序)
Data sharing of the 835 postgraduate entrance examination of software engineering in Hainan University in 23
城联优品入股浩柏国际进军国际资本市场,已完成第一步
Mongodb client operation (mongorepository)
JS+SVG爱心扩散动画js特效
A brief history of deep learning (II)
第六篇,STM32脉冲宽度调制(PWM)编程
Dell筆記本周期性閃屏故障
浅谈测试开发怎么入门,如何提升?
【JokerのZYNQ7020】AXI_EMC。
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis
Stm32f407 ------- DAC digital to analog conversion
If the college entrance examination goes well, I'm already graying out at the construction site at the moment
深度学习之线性代数
A brief history of deep learning (I)
Configuring the stub area of OSPF for Huawei devices
重上吹麻滩——段芝堂创始人翟立冬游记
什么是时间
【批处理DOS-CMD命令-汇总和小结】-跳转、循环、条件命令(goto、errorlevel、if、for[读取、切分、提取字符串]、)cmd命令错误汇总,cmd错误
ZYNQ移植uCOSIII