Yash
Yash

Reputation: 173

How to search files using batch file and get the relative file path not the full path?

I want to search files with .log extension recursively in a directory. I am trying like below command in a batch file.

for /R  %%A in (*.log) do echo %%A >> All_logs.txt

I tried this also:

for /R  %%A in (*.log) do echo %%~nxA >> All_logs.txt

But I am either getting full path like this:

D:\Folder1\sub_folder1\bootmicro.log
D:\Folder1\sub_folder2\debug.log 

or

bootmicro.log
debug.log

respectively.

Since I am running the batch file in the path D:\Folder1, I want search result to be like:

sub_folder1\bootmicro.log
sub_folder2\debug.log

Further, in the same batch file, I want to create folders using the resultant file names as below:

sub_folder1_bootmicro_log_Analysis
sub_folder2_debug_log_Analysis

or

sub_folder1_bootmicro.log_Analysis
sub_folder2_debug.log_Analysis

How can I do this all?

Upvotes: 1

Views: 785

Answers (2)

Paul
Paul

Reputation: 2710

Similar with forfiles

for /F "usebackq delims=" %%a in (`forfiles /s /m *.txt /C "cmd /c echo @relpath"`) do (
  set "myfile=%%~a"
  setlocal EnableDelayedExpansion
  set "myfile=!myfile:~2!
  for %%c in ("!myfile:\=_!") do (
    endlocal
    echo md "%%~c_Analysis"
  )
)
Exit /B

Upvotes: 0

MC ND
MC ND

Reputation: 70943

When you call xcopy with a relative path you get a list of files to copy (the /l means only get the list) with relative paths.

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=1,* delims=\" %%a in ('
        xcopy /l /s .\*.log "%temp%"
    ') do if not "%%b"=="" echo(%%b

The for /f loop will process the list removing the starting .\ (using the backslash as delimiter) for each file in the list.

As the output from xcopy will contain and ending line with the number of files, and this line will not have a second token, the if has been included to avoid an empty line at the end.

edited For the folder creation, delayed expansion will be needed to handle the string replacement, but to prevent problems with ! included in any of the files/folders names, it needs to be enabled/disabled where needed.

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=1,* delims=\" %%a in ('
        xcopy /l /s .\*.log "%temp%"
    ') do if not "%%b"=="" (
        echo(%%b
        set "target=%%b"
        setlocal enabledelayedexpansion
        for %%c in ("!target:\=_!") do (
            endlocal
            md "%%~c_Analysis"
        )
    )

Upvotes: 3

Related Questions