Georgep2000 February 2016

using batch to find files with a wildcard and print the name to another file

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

Answers


rojo February 2016

search.bat:

@echo off & setlocal
for /r "%~dp0" %%a in (*.txt) do call env.bat "%%~nxa"

env.bat:

@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.

search.bat:

@echo off & setlocal
for /r "%~dp0" %%a in (*.txt) do (@echo %%~nxa|env.bat)

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:

search.ps1

set-executionpolicy remotesigned
gci -recurse -filter *.txt | %{ .\env.ps1 $_.Name }

env.ps1

set-executionpolicy remotesigned
param (
    [string]$filename
)

$filename

And next is the stdin method.

search.ps1

set-executionpolicy remotesigned
gci -recurse -filter *.txt | %{ $_.Name | .\env.ps1 }

env.ps1

set-executionpolicy remotesigned
[string]$filename = $input

$filename

Post Status

Asked in February 2016
Viewed 1,040 times
Voted 9
Answered 1 times

Search




Leave an answer