Reputation: 39
My issue is that i would like to search a folder with a wildcard and then print the name of the file in another batch file. For example: c:\docs\hello.txt (I want to look through this folder with a *.txt search criteria then pass this "hello.txt" to my env.bat with set filename=
So far i can get the filename as below:
echo off
cd %1
if exist filelist.txt del filelist.txt
for /r %%a in (*.txt) do echo %%a > filelist.txt
Upvotes: 1
Views: 5466
Reputation: 24466
@echo off & setlocal
for /r "%~dp0" %%a in (*.txt) do call env.bat "%%~nxa"
@echo off & setlocal
set "filename=%~1"
echo %filename%
search.bat
will search the directory in which the script lives recursively for *.txt
. For every match, env.bat
is called with an argument of the filename.txt (without the full path, if you want the full path, change "%%~nxa"
to "%%~fa"
. See help for
in a console window for more info.) env.bat
then echoes the variable it set.
Just as an academic exercise, it's also possible to pass filename.txt
via stdin rather than as a script argument.
@echo off & setlocal
for /r "%~dp0" %%a in (*.txt) do (@echo %%~nxa|env.bat)
@echo off & setlocal
set /P "filename="
echo %filename%
For Eric J., here are the same scripts written in powershell. First is the argument method:
set-executionpolicy remotesigned
gci -recurse -filter *.txt | %{ .\env.ps1 $_.Name }
set-executionpolicy remotesigned
param (
[string]$filename
)
$filename
And next is the stdin method.
set-executionpolicy remotesigned
gci -recurse -filter *.txt | %{ $_.Name | .\env.ps1 }
set-executionpolicy remotesigned
[string]$filename = $input
$filename
Upvotes: 1