Displaying file names with a certain number of characters in command line
Solution 1
The wildcard ?
matches any character at most once, so dir ???????.txt
will match any .txt-file with an extension preceded by at most seven characters. There is no wildcard that matches any character exactly once that dir
directly supports, but the command's output can be piped into findstr
, which supports regular expressions.
In this case, dir /B | findstr /R "^.......\.txt"
will do the trick.
Solution 2
I wrote a batch file that examines the output of dir ???????.txt
and echoes only the files that have 7 characters (11, including .txt).
@ECHO OFF
REM --- Call Subroutine for all files of Len 1 - 7 characters ---
For /f "delims=*" %%a in ('dir "c:\???????.txt" /b') do Call :CheckLen %%~nxa
REM --- End Batchfile ---
Goto :eof
:CheckLen
REM --- Place Filename in Variable FNAME ---
Set FName=%*
REM --- IF Valiable FName <> First 10 characters of FName, FName has ---
REM --- 11 Characters (7 + .txt). Echo Output ---
if NOT "%FName%"=="%FName:~0,10%" Echo %FName%
Note: In line 'dir "c:\???????.txt" /b'
,add /s
if you want also to search the subdirectories of C:. This will probably take a long time without output.
Solution 3
DIR /b /s | findstr /r /i "\\.......\.txt$"
Related videos on Youtube
batsta13
Updated on September 18, 2022Comments
-
batsta13 almost 2 years
I need to list all text files on the C drive whose names are seven characters long. I tried the following command
DIR ???????.txt
However, this command displayed files with seven characters and less. Which command could I use to only display files with seven characters?
-
batsta13 over 12 yearsthanks this seems to work as i'm new to scripting is their a simpler way of doing it.
-
Marcks Thomas over 12 yearsAs far as I know, the ?-wildcard has matched zero or one character ever since MS-DOS. Likewise, the character
?
is used in regular expressions to match the preceding element zero or one times, but after some digging, it seems there is more to it. Apperently,?
will only match zero characters when it preceeds either another wildcard, a dot or the end of a string, in Windows 7, that is. How convenient! -
ZEDA-NL over 12 yearsI love this solution. It took me a while though to figure out how I can use it with subdirectories (dir /b /s) because it also returned files like c:\test\aa.txt (yes, test\aa has 7 characters too). I found the solution in the commandline: dir /B /s| findstr /R "\[^\][^\][^\][^\][^\][^\][^\ 3;\.txt$"
-
slhck about 11 yearsWelcome to Super User! Instead of just posting a line of code, please explain what it does as well. Edit your post to add more info. Thanks.
-
tgkprog about 11 yearsmaybe empty string is a character for them. but they should write it better and give 2-3 examples along with find str