简体   繁体   中英

How to replace first word in string using batch?

Hello StackExchange community!

I am trying to solve the problem of replacing the first word in a row with the other. Type of conversion depends on the first letter of the word.

To the point. I have a log file (INPUT.txt) in the following form:

s272400 616264890454 23.19 14.79
s272400 616264890453 25.11 16.23
s272400 616264890452 24.12 15.73
u272400 616264890451 21.18 16.78
s272400 616264890450 24.19 12.12
u292402a 616264890449 21.18 18.98
s292402a 616264890448 20.13 15.73

I would like to look like this:

w1 616264890454 23.19 14.79
w1 616264890453 25.11 16.23
w1 616264890452 24.12 15.73
w2 616264890451 21.18 16.78
w1 616264890450 24.19 12.12
w2 616264890449 21.18 18.98
w1 616264890448 20.13 15.73

If the string starts with the letter "s" I would change the begining of substring to "w1" if you begin with the letter "u" I would change substring to "w2" as in the example above. The first substring may be of different lengths.

I wrote the code here:

@echo off
setlocal enableextensions disabledelayedexpansion
set "Ver_1=s"
set "Ver_2=u"
set "Ver_1_res=w1"
set "Ver_2_res=w2"
for /f "delims=" %%a in (INPUT.txt) do (
    set var=%%a
    setlocal enabledelayedexpansion
    set value_1=%Ver_1%
    set value_2=%Ver_2%
    set value_res_1=%Ver_1_res%
    set value_res_2=%Ver_2_res% 
    set ProgramVersion=!var:~0,1!

if !ProgramVersion!==!value_1! (
set "var=!value_res_1!"
echo !var!
)
if !ProgramVersion!==!value_2! (
set  "var=!value_res_2!"
echo !var!
)
endlocal
) >> OUTPUT.txt
pause

The result (OUTPUT.txt) of this script is as follows:

w1
w1
w1
w2
w1
w2
w1

Conversion work but lose other information from the log. I am sure that the problem is trivial, but for a long time already, I can not solve it. Please help!

@echo off
setlocal enabledelayedexpansion
(FOR /f "tokens=1,*" %%a IN (input.txt) DO (
  set a=%%a
  if "!a:~0,1!"=="s" set b=w1
  if "!a:~0,1!"=="u" set b=w2
  echo !b! %%b
))>output.txt

when you set the var like "set "var=!value_res_1!" or "set "var=!value_res_2!", you lose the remaining info. you need to add the remaining data to var when you do the set.

In this method it is simpler to add or modify replacement values; it also run slightly faster...

@echo off
setlocal EnableDelayedExpansion

rem Define the replacement values
set "res[s]=w1"
set "res[u]=w2"

(for /F "tokens=1*" %%a in (input.txt) do (
   set "var=%%a"
   for /F %%c in ("!var:~0,1!") do echo !res[%%c]! %%b
)) > output.txt

You may review the management of arrays in Batch files at this site .

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