简体   繁体   中英

Windows scripting string manipulation to remove alpha characters

I am a Linux guy and trying to learn batch scripting.

I have the following requirement to manipulate the string.

set string=1.23.10xxxx2

I wanted to remove the alpha characters from the above string.

i need the output as 1.23.102 or 1.23.10, both outputs are fine to me, could anyone please help me.

@echo off
set remove=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

set string=1.23.10xxxx2
for /F "tokens=1,2 delims=%remove%" %%a in ("%string%") do (
   echo Part before removed chars: %%a
   echo Part after  removed chars: %%b
   echo Both parts: %%a%%b
)

If the format has a consistent length, then you can simply use sub-string operations.

To get 1.23.10:

set "string=%string:~0,7%"

To get 1.23.102:

set "string=%string:~0,7%%string:~-1%"

If you are simply removing the character x , then use search and replace (always case insensitive):

set "string=%string:x=%"

All of the above are described in the help, accessed by help set or set /? .

But I suspect that none of the above will meet your needs. There is nothing built into batch to conveniently search and replace ranges of characters. You could use a FOR loop to iteratively search and replace each letter. This requires delayed expansion because normal expansion occurs at parse time, and the entire FOR construct is parsed in one pass.

setlocal enableDelayedExpansion
for %%C in (
  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
) do set "string=!string:%%C=!"

The above works, but it is relatively inefficient.

There are any number of 3rd party tools that could efficiently solve the problem. But non-standard executables are forbidden in some environments. I've written a hybrid batch/JScript utility called REPL.BAT that works extremely well for this problem. It works on any modern Windows machine from XP onward. Click the link to get the script. Full documentation is built into the script.

Assuming REPL.BAT is either in your current directory, or better yet, somewhere in your PATH, then the following will work:

for /f "eol=a delims=" %%S in ('repl "[a-zA-Z]" "" s string') do set "string=%%S"

You can use GNUWin32 sed :

@ECHO OFF &SETLOCAL
set "string=1.23.10xxxx2"
FOR /f %%a IN ('echo %string% ^| sed "s/[a-zA-Z]\+//"') DO set "newstring=%%a"
ECHO %newstring%

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