johamtl
johamtl

Reputation: 3

How to replace strings in a batch file? Delayed Expansion and for loop is in use

I have this data source RESIDENTIAL.dat sample :

41-22-01-101-601         20   RANCH                 0       0   3   1   0       0       0       01 WALL  CCP  (1 STORY)       0TREATED WOOD                0ALUM., VINYL       0       0FORCED AIR W/ DUCTS        0C    0 

It's one row of the data source.I would like to remove all the "-" of the first value for each row , e.g, here it's 41-22-01-101-601.

Here is my bat code:

@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (RESIDENTIAL.dat) do (
set line=%%a 
set chars=!line:~0,16!
set str=!chars:-=!
set pp=!line:%chars%=%str%!
echo !pp!>>residential_new.dat
)

The result I got is

=

After testing, the problem is here

set pp=!line:%chars%=%str%!   

Can anyone help me with it?

Thank you very much!

Upvotes: 0

Views: 317

Answers (1)

Stephan
Stephan

Reputation: 56165

if there are tokens, you should use them:

setlocal enabledelayedexpansion
(
  for /f "tokens=1,*" %%a in (RESIDENTIAL.dat) do (
    set first=%%a
    echo !first:-=! %%b
  )
)>residential_new.dat

first token %%a is everything until the first space or tab, the second token %%b is the whole rest after the first space or tab. Do the changes in the first token and output the changed first token plus the "rest-token".

Upvotes: 2

Related Questions