'File name pattern matching in Windows command line
I have several files like:
a.txt
a$.txt
a$b.txt
b.txt
b$.txt
b$c.txt
I would like to print file whose name does not contain '$' using Windows command line for file name pattern matching like regular expression:
for %%f in ([^$]+.txt) do type %%f
or
for %%f in ([a-zA-Z]+.txt) do type %%f
But it does not work. How can I do this using Windows command line? Thanks!
Solution 1:[1]
The for
loop, like almost all cmd
commands, does not support something like regular expressions. The only command that supports a tiny excerpt of those is findstr
, which can be used together with dir
to get the desired result:
@echo off
for /F "delims= eol=|" %%f in ('
dir /B /A:-D "*.txt" ^| findstr "^[^$][^$]*\.txt$"
') do (
>&2 echo/%%f
type "%%f"
)
This could even be simplified by replacing the portion findstr "^[^$][^$]*\.txt$"
with find
/V "$"
.
Solution 2:[2]
As 'Windows command line' includes powershell.exe
as well as cmd.exe
, I thought I'd offer a powershell based idea too.
Directly in powershell:
Get-Content -Path 'C:\Users\Xiagao\Desktop\*.txt' -Exclude '*$*.txt'
In cmd/batch-file, but leveraging powershell:
PowerShell -NoP "GC 'C:\Users\Xiagao\Desktop\*.txt' -Ex '*$*.txt'"
You would obviously modify the path to your source files location, (use .\*.txt
for the current directory).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Compo |