Jader Dias
Jader Dias

Reputation: 90475

How to remove prefixes in strings on Windows command line?

Suppose I wanted to echo every executable inside the %programfiles% folder

cd %programfiles%
for /r . %i in (*.exe) do echo "%~i"

but it yields

c:\program files\program1\program1.exe
c:\program files\program2\program2.exe

and I want

program1\program1.exe
program2\program2.exe

How to remove those prefixes?

Upvotes: 6

Views: 3903

Answers (3)

Ste
Ste

Reputation: 2293

This answer is based on jebs

This one is if your batch file is not on the same drive as that you're working on so a different approach needs to be taken.

The code has comments included.

@echo off
::
rem Based of the answer: https://stackoverflow.com/a/6335341/8262102
title Removes prefix from directories example...
set "dirBase=C:\Program Files\Common Files"
cd /d %dirBase% &rem changes to the directory.
setlocal DisableDelayedExpansion
for /r . %%A in (*.exe) do (
  set "progPath=%%~A"
  setlocal EnableDelayedExpansion
  set "progPath=!progPath:%dirBase%=!"
  echo .!progPath!
  endlocal
)
echo/ & pause & cls

Upvotes: 0

jeb
jeb

Reputation: 82307

You could use the string replace function of batch

pushd %programfiles%
set "prefix=%programfiles%"
setlocal DisableDelayedExpansion
for /r . %i in (*.exe) do (
  set "progPath=%~i"
  setlocal EnableDelayedExpansion
  set "progPath=!progPath:%prefix%=!"
  echo !progPath!
  endlocal
)
popd

Upvotes: 9

adarshr
adarshr

Reputation: 62583

Put this in a batch file and run, it should do the job.

@echo off
setlocal ENABLEDELAYEDEXPANSION
cd %programfiles%
for /r . %%i in (*.exe) do (
    set pth=%%~fi
    set val=!pth:%cd%\=!
    echo !val!
)

Upvotes: 5

Related Questions