0

This most likely a very simple question, but here goes.

I need to search a file for numbers in a certain sequence, then add 5 to each number/ Ex:

time hr:1,st:2,ps:10 (is what i would be looking for - there will be all kinds of other numbers throughout the file)

I would like it to replace the numbers with the +5

time hr:6,st:7,ps:15

1 Answer 1

0

Batch is not an optimal choice for text processing, especially something as complex as your requirement. It could be done much more simply using JScript, VBScript, or powershell. But it is possible with batch...

There is not any simply batch command that can do what you want. You will have to write your own code to read each line, and if it does not match the format, write it out unchanged. If it does match the format, parse the line to extract the numbers, use SET /A to increment them, and write out the new line.

You cannot modify your file directly. Instead you must write to a temp file. When finished, move the temp file to the original name.

I will assume the formatted text of interest is not embedded within a larger line.

You give no indication as to other content within the file. Blank lines and perhaps exclamation points can cause issues. I'll assume they may be present, so the code is significantly more complicated than is needed if they are not.

I protect empty lines by using FINDSTR /N to insert a line number prefix for each line. This prefix must be stripped before writing out the line to the new file.

Exclamation points are protected by toggling delayed expansion on and off within the loop. If delayed expansion were enabled when a FOR variable is expanded, then the value would be corrupted if it contained an exclamation point.

@echo off
setlocal disableDelayedExpansion
>"yourFile.txt.new" (
  for /f "delims=" %%L in ('findstr /n "^" "yourFile.txt"') do (
    for /f "delims=:, tokens=1-7*" %%A in ("%%L") do (
      if "%%B %%D %%F%%H" equ "time hr st ps" (
        set /a "hr=%%C+5, st=%%E+5, ps=%%G+5"
        setlocal enableDelayedExpansion
        echo time hr:!hr!,st:!st!,ps:!ps!
        endlocal
      ) else (
        set "ln=%%L"
        setlocal enableDelayedExpansion
        echo(!ln:*:=!
        endlocal
      )
    )
  )
)
::move /y "yourFile.txt.new" "yourFile.txt" >nul
type yourFile.txt.new
1
  • OK, Thanks, I will play with that.
    – cjh7103
    Oct 28, 2014 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.