简体   繁体   中英

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?

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

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!
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM