I'm trying to list out file names excluding their extension,
How I want it:
File1
File2
File3
How it currently is:
File1.txt
File2.txt
File3.txt
I tried using
@echo off
dir /A:-D /B
pause
but it isn't working. I tried it in both a batch file and in command prompt.
Am I using the right command?
/B - (Bare format) Displays only file names.
If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”. Run the following command to remove the extension from the file.
List Files Using “Grep” Command: First, we will use the grep command within the “ls” list command to list all the files residing in the particular folder. Try the below “ls” command along with the “-la” flag to list all the regular files, e.g., hidden or not.
To list files in Windows using Command Line, first, open up the Command Prompt, then utilize the “dir” command. This will list the folders and files in the current directory.
For example, assuming the extension is always .txt
:
for %f in ("*.txt") do @echo %~nf
Instead of using DIR, we are using the FOR command to go through the list and sending each one to ECHO, with the "~n" option inserted into the %f, to cause the extension to be not shown.
An alternative is
FORFILES /c "cmd /c echo @fname"
However with this I get quotation marks around each output filename, which isn't what you want.
for %%f in ("*.txt") do @echo %%~nf
As long the directory doesn't contain any subdirectories whose names have an extension, you can generalise the *.txt
to *.*
:
for %f in ("*.*") do @echo %~nf
Where the file has an extension but nothing before it, e.g. .gitignore
, the resulting empty ECHO
command will output an inane message, such as ECHO is on.
To avoid this, you can filter out lines containing ECHO is
, with the FIND
command and the /V
option:
for %f in ("*.*") do @echo %~nf | find /v "ECHO is"
Of course if your local language causes DOS to output something other than ECHO is
then this filtering will not work. And it will miss any file that happens to contain ECHO is
in the filename.
for /R %f in ("*.png") do @echo %~nf | find /v "ECHO is"
This craziness, but this is the agonising price we pay for using Batch language instead of any other language (at ALL!). I am like an alcoholic, promising to all and sundry that I will never write a line of Batch code again, and then finding myself coming back to do so again, sheepishly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With