Use %~n twice on a string in Batch - batch-file

I've got some for loops iterating over files listed in a text file. They have two extensions, like filename.foo.bar.
The first loop goes:
for /F "tokens=*" %%A in (bars.txt) do decompressBars.exe %%A
This decompresses the .bar extension and leaves all the files as filename.foo. Next,
for /F "tokens=*" %%A in (bars.txt) do convertFoos.exe %%~nA %%~n~nA.baz
Here I'm trying to convert .foo files to .baz files with the convertFoos utility, but to do so I need to manipulate the %%A string to remove both file extensions, which I can't figure out how to do. I know that one ~n removes one extension, but two don't seem to remove two like I expected and I can't find a good way to do it. I would like to avoid scanning the folder for .foo files again as I might want to leave other .foo files in there untouched, but if there's no other reasonable way to do it I can avoid having other .foo files in the same folder.

You can remove the extension part twice, by making a call, that reinterprets its arguments:
for /F "tokens=*" %%A in (bars.txt) do decompressBars.exe %%A
for /F "tokens=*" %%A in (bars.txt) do call :convertFoos "%%~nA"
::Code should continue here
::Prevent reaching the "method"
exit /b
:convertFoos
convertFoos.exe %1 "%~n1.baz"
exit /b

Related

How to clean-up file paths (back/forward slashes) provided as arguments in a .bat script to avoid syntax errors

I have a simple .bat script which renames all files in a folder using ren. The input argument is a path to a folder containing the files to be renamed. The script sometimes returns syntax errors which we've traced to the fact that sometimes the input path has forward slashes, backslashes, or a mix of both (and sometimes starts with a double forward slash). We would like to make this script more robust by allowing it to accept any of these types of paths, and cleaning up the path as part of the .bat script before calling the ren command.
So my question is: is there a (set of) command(s) I can apply to the file path argument (%1 in the example below) before calling the ren function that will correct all forward/backslashes to be consistent and avoid syntax errors? I don't have much experience with .bat scripts, so any code examples would be helpful.
#echo off
setlocal ENABLEDELAYEDEXPANSION
for %%F in (%1*.nc) do (
for /F "tokens=1-8 delims=_" %%a in ("%%~nF") do (
ren "%%F" "%%a_%%b_%%c_%%d_%%e_%%g_%%f_%%h.nc"
)
)
UPDATE: In the end, only the last suggestion by Magoo was needed, because changing %1 to "%~f1" fixed the slash issues. I also had to add %~f1\ to the first argument of the ren command because otherwise it was somehow looking in the wrong folder (the first for found the files ok, but the ren command was looking in the wrong folder.
#echo off
setlocal ENABLEDELAYEDEXPANSION
for /F "delims=" %%F in ('dir /b /a-d "%~f1\*.nc"') do (
for /F "tokens=1-8 delims=_" %%a in ("%%~nF") do (
ren "%~f1\%%~nF.nc" "%%a_%%b_%%c_%%d_%%e_%%g_%%f_%%h.nc"
)
)
set "corrected=%~1"
set "corrected=%corrected:/=\%"
Then use %corrected% in place of %1 AND quote the filename thus:
for %%F in ("%corrected%*.nc") do (
If %1 is always a directory-name, then add
if "%corrected:~-1%" neq "\" set "corrected=%corrected%\"
as a third set line before the for line.
The first set assigns the value of %1 to a variable corrected - the ~ removes any enclosing quotes.
The second set changes all strings matching that between the : and = into that between the = and % in the variable given and assigns to the first-mentioned variable (can be the same variable, as in this case)
The third set, if used, checks that the last character is \ and if it is not, appends a \.
The quoting of the filename-string allows there to be spaces in the path/filename and is harmless if there are no spaces.
To avoid attempting to rename a file twice, instead of
for %%F in ("%corrected%*.nc") do (
use
for /F "delims=" %%F in ('dir /b /a-d "%corrected%*.nc"') do (
This builds a list of filenames in memory, then processes that list.

Rename files using batch file - original file name varies

I am trying to rename a bunch of files that have random characters at the beginning of the file name.
For example I have these: 63edaa55dfh33_Section1.pdf, 63edaa55dfh33_Section2.pdf, 63edaa55dfh33_Section3.pdf
I want to rename them to Section1.pdf, Section2.pdf and Section3.pdf.
The problem is the "63edaa55dfh33_" part may change so basically I want to remove everything up to and including the _ from every file. I tried using rename "*.pdf" "////*.pdf" as a test but it didn't work. The first 2 files were renamed properly with the first 4 characters removed but the 3rd file had the first 8 characters removed for some reason.
This solution may also not work because I don't always know the number of characters I want removed,that is why I want a way to say remove everything up to and including the _.
Run this on the command line in your pdf folder:
for /f "tokens=1,* delims=_" %a in ('dir /B *.pdf') do #echo %a_%b %b
That will give you a feel for how it works. Basically, the"tokens=1,* delims=_" causes the output from the dir /B *.pdf command to be split into pre and post delim parts (%a and %b respectively). In a batch script you need to double all the percent symbols:
#for /f "tokens=1,* delims=_" %%a in ('dir /B *.pdf') do #ren %%a_%%b %%b

batch file to get file name up to specified character

I have filenames in a directory in the format of Mumbai Short Call Agentwise-MUMBAI SHORT CALL-3-01092016. I would like to strip off everything after the second hyphen and keep the first portion of the filename.
Is there a good website that could direct me in how to accomplish this? Or, maybe one of you dos batch experts can lead me in how to do this?
for /f "tokens=1,2,* delims=-" %%a in ('dir /b *-*-*') do #ECHO ren "%%a-%%b-%%c" "%%a-%%b%%~xc"
for every file with the given mask *-*.*: get first (%%a) and second part (%%b) plus extension of the rest (rest: %%c; Extension of the rest:%%~xc)
Notes:
- if you shorten filenames, be aware of possible duplicates!
#ECHO just lists the rename commands. Remove #ECHO, if the output satisfies you
See for /? or for /f for more information

Batch Script assistance needed

Happy Friday Think-Tank!
I need some assistance with a Batch .BAT script. Specifically I need help with some "IF statement syntax"
I have a script that is renaming files. There are two files, one ending in four digits and the other ending in five digits. The files will be renamed with variables I have already pre-set earlier within my script.
So here is a scenario: We have two files in a directory located at
c:\Users\username\Desktop\test-dir
There are two files within test-dir:
file1.12345
file2.1234
A four digit ending is one variable type (VAR1), whereas a file ending in five digits is another variable type (VAR2).
I need an if statement to:
a) read all the files(s) with the chosen directory (without using a wildcard if possible).
b) determine based on the number of digits after the "." which variable to use.
c) once making that determination rename the file with the appropriate variables.
The final re-naming convention is as so: yyyymmddtype.1234/12345
So basically it would use the datestamp variable I already created, the type variable I already created to be injected by the if statement, and append with the original ending digits of the file.
I know this seems like a lot, but I am more so a bash script guy. I have all the elements in place, I just need the if statement and what feels like a for loop of some kind to tie it all together.
Any help would be great!
Thank you!
Sorry, not the option you where asking for. Instead of iterating over the full list checking each file for extension conformance, iterate over a list of patterns that will filter file list, renaming matching files with the asociated "type"
for %%v will iterate over variable list, for %%a will split the content of the variable in pattern and type, for %%f will generate the file list, filter with findstr using the retrieved pattern and rename matching files with the corresponding "type"
Rename command is preceded with a echo to output commands to console. If the output is correct, remove the echo to rename the files.
#echo off
rem Variables defined elsewhere
set "folder=c:\somewhere"
set "timestamp=yyyymmdd"
rem Rename pattern variables in the form pattern;type
set "var1=\.....$;type1"
set "var2=\......$;type2"
set "var1=\.[^.][^.][^.][^.]$;type1"
set "var2=\.[^.][^.][^.][^.][^.]$;type2"
setlocal enableextensions disabledelayedexpansion
for %%v in ("%var1%" "%var2%") do for /f "tokens=1,* delims=;" %%a in ("%%~v") do (
for /f "tokens=*" %%f in ('dir /a-d /b "%folder%" ^| findstr /r /c:"%%~a"') do (
echo ren "%folder%\%%~f" "%timestamp%%%~b%%~xf"
)
)
endlocal
#ECHO OFF &SETLOCAL
set "yyyymmdd=yyyymmdd"
set "VAR1=VAR1"
set "VAR2=VAR2"
for /f "delims=" %%a in ('dir /b /a-d^|findstr /re ".*\....."') do echo(ren "%%~a" "%yyyymmdd%%VAR1%%%~xa"
for /f "delims=" %%a in ('dir /b /a-d^|findstr /re ".*\......"') do echo(ren "%%~a" "%yyyymmdd%%VAR2%%%~xa"
remove echo( to get it working.
If I understand you then this will rename the two files using preset variables for each one:
for %%a in ("%userprofile%\Desktop\test-dir\*") do (
if "%%~xa"==".12345" ren "%%a" "%variableA%-%variableB%%%~xa"
) else (
ren "%%a" "%variableC%-%variableD%%%~xa"
)
)

Extracting A List Of Phrases From A Large TXT File, And Writing A Single TXT File With Each Phrase (Also the title of that file)

I have a list of terms, and I have large text files containing some of those terms. My task is to come up with one text file for each of the terms in the same directory as the original text file.
BEFORE
listofterms.txt (apple cores, peaches, roast beef, things wrapped in nori, etc...)
LargeFileOfFoodWords.txt (ranging from 20-20,000 individual lines of non-duplicated text)
AFTER
apple cores.txt, peaches.txt, roast beef.txt, things wrapped in nori.txt (etc...)
LargeFileOfFoodWords.txt (original file, unchanged--or if possible, with all 'listofterms' extracted)
With the following bat file, I am able to do this with a SINGLE word. However the resultant file contains the paths of ALL files within the directory the batch file resides in. Successive searches also include apple cores.txt, peaches.txt, etc...
So I have some elements working, and need to tweak the following to:
not search any files but those I choose
include ONLY extracted text without metadata
continue searching and writing files until reaching the bottom of my list of search terms
This script will work with any .txt file and give you the resultant "SearchTerm.txt," if you wish to test it yourself.
#echo off
set RESULT_FILE="result.txt"
set /p "buck1=Enter Bucket Word or Phrase to find:"
pushd %~p0type NUL > %RESULT_FILE%.tmp
for /f "delims=" %%a in ('dir /s/-b/l *.txt')
do (for /f %%c in ('find /i /c "%buck1%" "%%a"')
do (for /f "tokens=*" %%f in ('find /i "%buck1%" "%%a"')
do if %%c neq 0 echo :`%%f))>>"%RESULT_FILE%".tmp
move %RESULT_FILE%.tmp %buck1%.txt >nul 2>&1
popd
this might work for you:
for /f "delims=" %%a in ('findstr /xg:listofterms.txt LargeFileOfFoodWords.txt') do (type nul>"%%~a.txt"&echo(%%~a>"result.txt")
For more help enter help for and help findstr.

Resources