简体   繁体   中英

“For” command and “findstr” in windows command prompt

In a different post, i found this solution to rename a file to the current date in the ISO-format:

FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO @SET B=%%A
copy test.java %B:~0,4%-%B:~4,2%-%B:~6,2%.java

I understand everything except this part:

 ^| FINDSTR \.

What does it do? As "WMIC OS GET LocalDateTime" has this format

LocalDateTime
20150223064808.538000+060

i am assuming it somehow limits the sting. But how?

There are a couple of things going on in that line.

^ is batch's escape character. It's there so that the next character won't break the for loop. | is a pipe, and it sends the output of the command on its left to the command on its right. FINDSTR searches for a string and returns any that it finds.

Here's where it gets a little complicated: \\ is findstr's escape character, and allows the next character to be interpreted literally. . is just a period, but without the preceeding \\ , it's a single-character wildcard (f.re would pick up fare and fire, etc.)

wmic os get localdatetime runs wmic and returns the local date and time, and its output looks like this:

LocalDateTime
20150223010540.071000-300

When you pipe it to findstr and tell findstr to return lines that contain a single period, you get

20150223010540.071000-300

And then the whole thing is inside a for /F loop so that the output of that command can be stored in a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM