Batch processing (BAT) command Some summary of learning _dos/bat

Source: Internet
Author: User
Tags goto printable characters rar first row

One, set article:

1, set (no switch)

Set. =test
Set.
:: If a variable begins with: \. These three path-related symbols, you can omit a space by using set to view variables that begin with that character.
Echo%tmp:*\=%
:: Shows the part of the TMP variable after the first \, the remaining variable substitution and the variable offset too simple do not explain

2. set/p variable name = annotation < device name
When the device name is a file, because the newline character in the file is associated with a carriage return, only the first row of the file is taken as the contents of the Var variable, but not more than 1024 bytes, and when the device name is nul or COM3, only comments that do not wrap are displayed, in which case the variable name (for example: Set/p=hello World

3, set/a, one of the most skillful commands

set/a n=1,m=2
:: At the same time, different values were given to two variables
set/a a=b=c=d=e=f=1
:: Assigning values to multiple variables with a single formula
set/a "1/n" 2>nul| | echo variable n is not a pure number or zero
:: With the denominator can not be 0 characteristics, using set to determine whether a variable is not 0 pure digits
Set N=1
set/a "n=!! 123|!! 234&!! 0 "
:: Bit operations,!, ^, | and & are often used in Boolean operations, and logical displacements are often used in binary operations (>> can also determine whether a value is negative, see the following example)
set/a n=-100, "1/( -100>>31)" | | echo variable n is negative
:: Comply with the positive and negative in cmd storage characteristics, you can use the logical displacement to determine positive and negative "Boolean operation" can be derived from a wide range of algorithms, such as a slight change can be compared to two or even more than the size of the number
set/a n=~-100
:: Using ~ To turn all binary 1, 0 reversal, minus in the back or in the front can be achieved simply add 1 or minus 1, this technique is mainly used to reduce the use of parentheses, because the ~ and minus the priority is higher than the arithmetic operator
set/a test=%test:~5,1%-0
:: You can avoid errors when%test:~5,1% is empty
set/a decimal =0x 16 system, Decimal = 8
:: Fast hex and octal decimal, but no binary ...
: Loop
set/a n+=1001
Echo%n:~-3%
Goto Loop
:: This is more advantageous than the regular complement method
For%%a in (Test 123 ABC Test @#$ 123) do set/a ".%%a+=1"
Set. | findstr/v/e "= 1"
:: Classic scenario for getting the number of repetitions of a string

Second, for article:

This is the strongest internal command in the batch, not one!

1, for (no switch)

Copy Code code as follows:

For%%a in (c:\*.*) do echo%%a
:: Display all non-hidden, non-system properties files in C packing directory
For%%a in (. \ ...) do echo%%~nxa
:: Displays the folder name of the previous level of the directory
Set str=123,234,345
Set str=%str:,=\%
For%%a in (%str%\..) do Echo%%~nxa
:: With the previous technique, skillfully take the penultimate paragraph string, and for/f "delims=\" side by side
For%%a in (*.txt) do (
for/f "Useback delims="%%b in ("%%a") Do (
Set Str=%%b
For%%c in ("!STR: separator ="! ") do (
for/f "Tokens=1*"%%d in (%%c) do echo%%~d
)
)
)

:: For and for/f with no parameters, very powerful, just to cite this example
For%%a in (123) does for%%a in (234) does for%%a in (345) do echo%%a
:: In fact, if you read only the last-level for parameters, you can use the same parameters even for multiple-layered for nesting, such as%%a
For%%z in (!tmp!) do echo!%%z!
:: At present, the best way to get rid of call is to implement multi-layer variable nesting, many people use

2, for/l

FOR/L%%a in () do Echo
:: Infinite Loop, step number 0 is the same effect, but not this concise
FOR/L%%a in ( -4 1) do echo%%a
:: The three bits from left to right of the three parameters in for/l are the initial value, the step number, the termination point, and when the number of users given is insufficient, the insufficient item is assigned to 0 in the order from right to left.

3, FOR/D/R

FOR/R/D%%a in (*) do echo%%a
:: You can traverse all subfolders, the reason why you can use the r switch and D switch is because of the intersection of their parameters, L switch and F switch is not.

4, for/f

For/f itself is not particularly skillful, and its advantage is that it can analyze the output of other commands as input, so for/f can be said to be the king of the internal command.
for/f "tokens=* delims=0123"%%a in ("0000123456") do echo%%a
:: Removing the n characters of a prefix
for/f "skip=99"%%a in (1.txt) do echo 1.txt at least 100 lines
:: Before seeing a moderator wrote, the impression is quite deep.
FOR/L%%a in (1 1) Do (
for/f "tokens=1,2* delims=\"%%a in ("!tmp!") Do (
For%%c in (%%a%%b) do echo%%c
Set tmp=%%c
)
)
:: To expand the range of the value of tokens
Set tmp=123=234=345=456
FOR/L%%a in (1 1) Do (
for/f "tokens=1,2* delims=="%%a in ("!tmp!") Do (
Set Str=!str!,%%a,%%b
Set tmp=%%c
)
)
Echo%str:~1%
:: Sometimes set variable substitution is unable to replace some special characters, at this time you can use for/f processing
Set test=d:\test\
For%%a in (test.*) do (
If "%%~za" Neq "%%~z$test:a" replace/p/U "%%a" "%%~dp$test:a"
)
:: Determine if a file under the current directory with test name exists under the D:\test\ folder with the same name, if it exists and has a different size, and the modification date is earlier, it will not be processed. The "%%~dp$path:a" parameter in the For help information seems to have not been used, although the scope of its application is very narrow, but the specific circumstances may wish to try.
Setlocal enabledelayedexpansion
Set T=tmp
Set @=t
for/f%%a in (' echo!%@%! ') do echo!%%a!
:: Another three-layer nesting method, in fact, not practical.

Third, findstr article

My favorite command, unfortunately, the external command is too slow to start, so the actual use of less appearance.
FINDSTR/S/M. * *.*
:: In fact, Findstr is also a dir, although more slowly than Dir, but more to find the contents of the file function
findstr/n. * 1.txt|findstr "^5000:"
:: Very useful to take the specified line of methods, with the regular can take the specified range of lines
set/p n= Please enter numbers or uppercase and lowercase letters
(Echo!n!) | Findstr/i "[0-9a-z]" &&echo input wrong!
:: Is this practical enough? Do not explain
dir|findstr ['-Z]
:: To find rows with wide characters using the actual size order of characters in the findstr and if commands
Findstr/x "....." 1.txt
:: Find 10-byte rows in 1.txt
(Type 1.txt&echo;) |findstr/o. *|more +1
:: Plus for, it's easy to get 1.txt of bytes per line
findstr>1.txt/m/P. * *.*
dir/b/a-d|findstr>2.txt/v/i/m/g:1.txt
:: Gets the filename containing the nonprinting character, the key is the findstr fetch set
Findstr "^rar!"/g:1.txt
:: Here 1.txt is the last tip 1.txt, the content is all contain not printable characters of the file list, this technique can search RAR file, although simple, but has not been missed, original.
More>tmp +2 1.txt
Findstr> the first two lines. txt/x/v/g:1.txt 2.txt
:: Sometimes this method can be used to get the first few lines, of course, most of the cases are not for/f appropriate, and there are special character bugs
@echo off
findstr/n. * 1.TXT&GT;TMP1
find/n/V "" 2.TXT|MORE&GT;TMP2 +2
For/f "tokens=2*delims=]:"%%a in (' fc/n/lb10000 tmp1 tmp2^|sort ') do (
Echo;%%b
)
del tmp?
Pause
:: QZWQZW pioneered the idea of using fc/n to output dual text at the same time, but there are flaws in the sort that may be disrupted, so add a find to make up for it

Four, start, call, cmd article

are put together because the functions of these three commands intersect
1, start
@echo off
%1 cd.>tmp
set/p=%1
%1 start/b ""%0: (exit after five seconds) TM
If not '%1 ' = = ' ' goto%1 '
set/p N= Enter any character
If Defined n (
del tmp
echo you entered%n%, five seconds to exit.
else echo input is empty! Quit after five seconds.
: (Five Seconds to exit)
ping/n 5 Localhost>nul
If exist%2p exit
Pause
:: Magical start/b Let set/p realize choice delay function, do not know which predecessors first, once again praise one. The tips for% 1 and%2 are only for embellishment, I just think this "building blocks" is fun to impose.
2, call
Set A=b
Set B=c
Call Echo%%%a%%%
:: No variable delay can still be used to implement variable delay reading and nesting, but the efficiency is flawed
3, cmd
Set A=b
Set B=c
CMD/C Echo%%%a%%%
: This proves that the effect of a call to a command is approximate to cmd/c, and that the difference between the "for" and "if" commands cannot be run with call, because for and if are actually just keywords, not real commands
Set A=b
Set B=c
CMD/V:ON/C Echo!%a%!
:: Do not need setlocal, still can use variable delay
%1%0:: Echo; successfully invoke itself
%
:: Personally very common, here with the techniques of%1 and%2 for my preference, that:: Can be changed to REM. Although the cmd command does not appear here, it actually executes at cmd/c% 0.
@echo off
%1 cmd/v:on/c%0::
Set n=123
Echo!n!
Pause
:: Synthesis of the first two techniques to implement without using setlocal, open variable delay
@echo off
Set Str=test test 1234
Setlocal enabledelayedexpansion
For/f "delims=:;"%%a in ((cmd/u/C echo!str!^) ^&echo^;^;^) ^|findstr/o ^) do set/a n=%%a-5
for/f "delims=:"%%a in ((Echo!str!^) ^&echo^;^;^) ^|findstr/o ^; Do set/a d=n-%%a+3
set/a m=n/2,s=m-d
Echo is a total!m! character,!d! a single-byte character, and!s! a double-byte character
Pause
:: Three steps to determine given, two-character number of alternative methods. The advantage is that it supports the calculation of very long strings (at this time with more conventional algorithm steps and difficult to general), the disadvantage is low efficiency.
ren 1.exe 1.bat
Echo, double-click 1.bat
:: Why is this also possible to run? Because the EXE is opened in the "%1"%*,bat is cmd/c "%1"%*, so the EXE as a bat run, the equivalent of cmd/c 1.exe ... But this is only suitable for double click to open, in cmd internal call this file is the real bat run, so there will be errors.

V. Other ORDER Articles

1, Xcopy is much stronger than copy, the biggest regret is that it is an external command
XCOPY/A Source Folder destination Folder
:: Xcopy used in the screening is also very practical
XCOPY/L/y/n%cd%.
:: Skillfully take the current directory under the short name of the file, and will not really copy
xcopy/d:1-31-2011/l "%cd%" tmp\
:: Get the list of documents modified after January 31, 2011
xcopy/t *.txt C:\test\
:: Copy the directory structure containing TXT file to C:\test
@echo 1.txt>list
Xcopy/exclude:list? TXT test\
:: Copy all files with a single character name to the test folder
XCOPY/S *.txt. \txt\
:: Copy all TXT-named subfolders to the TXT folder in the previous level directory
for/f "delims="%%a in (' dir/s/b/ad^|sort-r ') do rd "%%a" 2>nul
:: The classic idea of removing empty folders, using rd defaults to remove empty folders without deleting attributes in Non-empty folders
FOR/D%%a in (*) do (
xcopy/q/h/r/s/k "%%a" "Tmp\"
RD/S/q "%%a"
ren "tmp" "%%a"
)
:: Alternative scenarios for removing empty folders
2, compared to the previous orders of the big guys, these orders are relatively humble, so grouped in a class of
Copy Nul+unicode.bat decryption. bat
:: To encode and confuse the encrypted bat with the Unicode file header, this command can be used to decrypt the
Echo>tmp 12323412 2323242134122434 345
more/t20 tmp> aligned. txt
Type is aligned to. txt
Pause
:: The t-switch of the more command has also large use, unspoken rules do not explain.
cmd/u/C Echo 0123456789|more
:: The more command converts the NUL character of the cmd/u output to a space, thus enabling the verbatim printing of one-byte characters per line.
@echo off&setlocal enabledelayedexpansion
Set n=32768
(For%%a in (16384 8192 4096 2048 1024, 256 8 4 2 1) do 128 Sort/rec!n! | set/a n+=%%a) >nul 2>nul
Echo's longest line has%n% characters
Pause
:: This may be used to determine the maximum number of characters for the longest line when the maximum number of line characters is greater than 128 (the REC switch will fail when it is less than 128). In the code that a lot of 2 of the N times is the word, the actual combat can be omitted some), supporting the long string, the calculation of large file efficiency is significantly better than the traditional algorithm, New binary method from plp626 reprint, sort of/rec switch is relatively chicken, think to go also only think of this use, see no precedent
ren 1.exe 1.bat
Echo, double-click 1.bat
:: Why can I change the exe to a bat suffix name? Because the EXE is opened in the "%1"%*,bat is cmd/c "%1"%*, so the EXE as a bat run, the equivalent of cmd/c 1.exe ... But this is only suitable for double click to open, in cmd internal call this file is the real bat run, so there will be errors. And for the same reason, it can also be changed to a COM or cmd suffix name to execute.
3, to introduce some of the techniques in the CMD window, of course, they are only "cheat" cmd window, once output to the file on the true colours:
@echo off
Echo 1
Echo 2
Echo 3
Echo is retrograde.
Pause>nul
:: This is too bull, I don't know who found it.
Set "dq="
(Echo 2, the importance of family planning%dq%.
Echo 1, implement the scientific concept of development%dq% WOW) |sort
:: By using the TAB key and backspace to achieve a multiline bundle sorting and the wrong line to display, tab and backspace between the space is the key, otherwise become regressive
set/p= display different colors on the same line:
set/p= Red Bottom Blue Word
echo Yellow Bottom Green Word
findstr/a:41. * Red Bottom blue word?
findstr/a:62. * Yellow bottom green word?
Del>nul Red Bottom Blue character yellow bottom green word
Pause
:: Often seen in the same line to display different colors of the method, but many people always use (four backspace four spaces), explained that did not understand the meaning of the backspace bar
@prompt $_
Dir fuck.tmp
Pause
:: Using this prompt, turn on the echo can be output at the same time command and command results, without unnecessary content, suitable for the production of bat run log
Echo
:: This black dot appeared in front of the introduction as a supporting actor, ANSI code in the 0X07, but also equivalent to the input in the CMD ctrl+g, it is displayed on the screen each time will be issued a "drip", so later findstr *.* must be careful (unless the last resort, Otherwise need to display the results to the window recommended plus/p switch), if accidentally printed out tens of thousands of, your computer will be like a telegram ringing non-stop, I recruit n times ...

Six, cmd operation mechanism Chapter

1, preprocessing mechanism: special character priority, sentence and chunk division
Setlocal enabledelayedexpansion
(Set n=3
set/a n=2,n=%n%+!n!+n)
:: Using the preprocessing mechanism to interpret a variable as multiple values
Setlocal enabledelayedexpansion
echo ^^!
:: When a variable delay symbol exists in the statement, it will be preprocessed two times, which is a must note
Set str=.
Set "str name=str"
For%%a in (%tmp%) do if defined%%a echo%%a exists variable str
:: Using for the parameter variable in the IF parameter to be interpreted after the feature, make up if defined for the space variable name compatibility flaw, the essential reason is for and if are special functions, their parameters set in the preprocessing of the block has been cmd "remember", It cannot be changed after that.
(Del%0
Echo can find me, I'll send you sugar.
Pause>nul)
:: The contents of the brackets are understood as a block, and the commands run without the need to read from the file, so even if the deletion itself can still run.
echo "Test&pause|sort
:: When an odd number of double quotes exists in a row of commands, all subsequent lines of characters are escaped
for/f tokens^=2delims^=^ "%%a in" ("123" Test "456") do echo%%a
:: By escaping special characters, use double quotes as delimiters in for
for/f tokens^=2delims^=^ "%%a in (^" 123 "456") do echo%%a
set/p=^ "" "
:: When a set of strings contains an odd number of double quotes, the workaround is to escape one of them, keep valid double quotes in pairs, but it cannot be escaped with the escape character, so the escape character should be placed outside the quotation mark to use
set/a "1/(%random%%%2)" &&set com=| | Set com=/f "tokens=2"
For%com%%%a in ("123 234 345") do echo%%a
:: If the random value is even, the second paragraph of the specified string is displayed, otherwise the whole segment is displayed. Using variables to customize commands is more flexible and easier than the conventional approach (one if and one command), but note that the variable delay is done after the block is interpreted, so the%com% cannot use the variable delay.
set/a \test1=123,test2=234
(@echo off
for/f "Tokens=1* delims=="%%a in (' set\ ') do echo%%b
) |sort
:: Sort sorts the output of the for command, and that @echo off is not superfluous, because before the channel is a block (for, if, or a statement wrapped in a pair of parentheses), the contents of that block will run as CMD/C, and the Echo is open at this time. The variable delay is closed by default.
Dir/ad 123\&&md234| | Rd 345&tree/f|more
:: When there are 123 folders, create 234 folders, or delete 345 folders, regardless of the results, the next screen will be the current directory tree. The emphasis is on the flexible use of pipeline commands and logical connectors
2, the magical handle
@echo off 2>nul 3>nul
This command does not exist ...
echo Error echo?
Pause
:: Handle backup, which can be used to mask all correct or incorrect echo
Cd.>1.txt 2>2.txt 3>3.txt 4>4.txt 5>5.txt 6>6.txt 7>7.txt 8>8.txt 9>9.txt
:: To create 9 files with one command, the efficiency is naturally increased
@echo off
(For/r%%a in (*.*) do del/f/S "%%~nxa" 3>> "%%a") 2>nul 4>>%0
Pause
:: Use the write handle to occupy the characteristics of the file to achieve efficient deletion of duplicate files
Cond...

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.