Reputation: 55
I'm trying to list all the files which have extra suffix after the extension E.g: .txt.1 or .txt.2 etc..
I'm using txt. but it's giving all the file names instead of only the files with extra suffix
for %%A in (*txt.*) do (call :renum "%%A")
after this I'm writing my program to rename the files accordingly. Can someone please check and help.
Upvotes: 3
Views: 390
Reputation: 10500
One solution would be to filter by extension inside the loop:
FOR %%A IN (*txt.*) DO (
IF NOT "%%~xA"==".txt" CALL :renum "%%A"
)
This works by using the "enhanced substitution of FOR
variable references", in this case %%~xA
. You can get an overview of all the available substitutions by executing FOR /?
.
Update:
IF /I
instead of plain IF
if case-insensivity is desired.name.txt.txt
will not be processed. If that's OK is not clearly stated, but rather likely.name_txt.ext
will be processed, which is due to the given wildcard *txt.*
and can be avoided by using *.txt.*
instead. My rationale to not change it in the first place was that only the OP knows his actual set of files, and I assumed he had a reason for choosing it (a situation common in these types of questions).Upvotes: 2
Reputation: 130819
I would use FINDSTR with DIR /B and FOR /F
The following will process names with any number of extra extensions like name.txt.ext
and name.txt.ext.ext
, etc. This includes a name like name.txt.txt
for /f "delims= eol=:" %%F in (
'dir /b /a-d *.txt.*^|findstr /i "\.txt\."'
) do call :renum "%%F"
This variation will only process names with a single extra extension like name.txt.ext
(including name.txt.txt
)
for /f "delims= eol=:" %%F in (
'dir /b /a-d *.txt.*^|findstr /i "\.txt\.[^.]*$"'
) do call :renum "%%F"
You might also check into my JREN.BAT regular expression file renaming utility. It can probably filter and rename all your files in one step, without any need for a custom batch script.
For example, the following will only rename files looking like "name.txt.ext", and transform them into "name_ext.txt"
jren "(\.txt)\.([^.]+)$" "_$2$1" /i
Upvotes: 1
Reputation: 34909
You could use two nested for
loops like this:
rem // Corrected file pattern (added a `.`):
for %%A in ("*.txt.*") do (
rem // Check (last) file extension:
if /I not "%%~xA"==".txt" (
rem // Remove (last) file extension:
for %%B in ("%%~nA") do (
rem // Check next-to-last file ext.:
if /I "%%~xB"==".txt" (
call :renum "%%~A"
)
)
)
)
According to the help of for
(type for /?
in a command prompt window), the ~x
modifier of the for
variable retrieves the file extension (which is the last dot .
and everything after). The ~n
modifier retrieves all but the file extension, hence the file (base) name. The code above uses two nested for
loops to get the last and the next-to-last file extensions and checking them against .txt
(in a case-insensitive manner).
Note that the call
command line is not executed for files ending in .txt.txt
.
Upvotes: 1