Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
Jader Dias Avatar asked Jun 13 '11 19:06

Jader Dias


People also ask

How do I delete a character in CMD?

To edit a command, use the left and right arrow keys to move around and the Backspace key to delete characters. You can enter commands that span more than one line. Delete next word (to the right of the cursor).

How do I edit the script in CMD?

However, if you are using a command file with the . cmd extension, Windows will think it is a command line script file and run it in the command line prompt. In this case, right-click the . cmd file and choose "Edit" or "Open with" or the Text Editor already associated with your command files in the popup menu.

How to SET variable value in CMD?

2.2 Set/Unset/Change an Environment Variable for the "Current" CMD Session. To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.

How to define variables in CMD?

Syntax SET variable SET variable=string SET "variable=string" SET "variable=" SET /A "variable=expression" SET /P variable=[promptString] SET " Key variable : A new or existing environment variable name e.g. _num string : A text string to assign to the variable.


1 Answers

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
like image 111
jeb Avatar answered Nov 15 '22 06:11

jeb