开发者

How to find a string and replace part of it using batch commands?

开发者 https://www.devze.com 2023-04-10 20:36 出处:网络
I have text file with lot of parameters with unique names. I need to find a parameter by its name and change the value of the parameter. The file looks something like this

I have text file with lot of parameters with unique names. I need to find a parameter by its name and change the value of the parameter. The file looks something like this

   ID      Value          Name
  4450     2.0        / [var_pot] 'DCF_loc'
  4451     100.0      / [var] 'DCF_t'
  4452     0.1        / [var] 'DCF_dur'
  开发者_C百科4458     1000.0     / [var] 'CommtF_t_P1'

For e.g. I need to find the parameter 'DCF_t' in the file and replace its value from 100 to some other value say 10. Unfortunately in my case, only the names and values of the parameters are in my control. I am in need of a batch file to do the "find and replace" job.

Please help me out...Thanks in advance...


in case it is Windows, you need to

  1. loop over all the lines of the file. try something like.. FOR /F %%a in (values.txt) DO echo %%a

  2. skip the first header line. Try FOR /f "skip=1" %%a in (%1) do echo %%a

  3. parse the contents of the line. Try FOR /f "skip=1 tokens=1-5" %%a in (%1) do echo %%b %%d

  4. check the fourth item. Try

    for /f "skip=1 tokens=1-5" %%a in (%1) do (
      if /i .%%e.==.'DCF_t'. (
        echo %%a  99.9  %%c  %%d  %%e
      ) else (
        echo %%a  %%b  %%c  %%d  %%e
      )
    )
    

and you almost done, or at least in your way to the solution. See HELP FOR and HELP IF for more information.


This is a little bit cryptic for batch beginners. And there are many better languages to do this job.
But it can be done also with batch.

The key is to rewrite the file and modify the correct line.

set "otherValue=10"
setlocal EnableDelayedExpansion
(
  For /f "tokens=1,2,*" %%a in (myFile.txt) do (
    set "var=%%c"
    if "!var!"=="!var:DCF_t=!" (
      rem ** not found, echo the line
      echo(%%a %%b !var!
    ) ELSE (
      rem ** Found the line
      echo(%%a %otherValue% !var!
    )
  )
) > outfile.txt

This assumes, that there are no exclamation marks in the text and that the lines are formatted always into three parts delimited by spaces or tabs.

0

精彩评论

暂无评论...
验证码 换一张
取 消