0

I wanted to modify each line of a .txt file in CMD by adding "0x" every two characters, any idea what command should I use inside the for?

The source.txt file would look something like this:

602A0020B1010008B9010008BB010008 
BD0185AC8B9010008BB10008BB010008
AC8B9010008BB100B9010008BB045809
602A0020B1010008

The output format that is expected to be obtained in the file result.txt or in the same source, would be the following:

0x60, 0x2A, 0x00, 0x20, 0xB1, 0x01, 0x00, 0x08, 0xB9, 0x01, 0x00, 0x08, 0xBB, 0x01, 0x00, 0x08,
0xBD, 0x01, 0x00, 0x08, 0xBF, 0x01, 0x00, 0x08, 0xC1, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,
...
  • 2
    Possible duplicate of [Batch adding a character every x characters](http://stackoverflow.com/questions/27297848/batch-adding-a-character-every-x-characters) – JosefZ Feb 13 '17 at 10:43

3 Answers3

0
@echo off&SetLocal EnableDelayEdexpansion

for /f "eol= delims=" %%a in (source.txt) do (
  call :showLine %%a
)
pause

:showLine
set line=%1
for /l %%a in (0 2 100) do (
  set n=!line:~%%a,2!
  if defined n (
    set /p=0x!n!,<nul
  ) else (
    echo;
    goto :eof
  )
)
goto :eof
0

Pure batch solution:

@echo off
setlocal enableDelayedExpansion
set "file=test.txt"
>"%file%.new" (
  for /f "usebackq delims=" %%A in ("%file%") do (
    set "ln=%%A"
    for /l %%N in (30 -2, 2) do if "!ln:~%%N!" neq "" set "ln=!ln:~0,%%N!, 0x!ln:~%%N!"
    echo 0x!ln!,
  )
)
move /y "%file%.new" "%file%" >nul


Using JREPL.BAT

call jrepl "^..|.." "0x$&,| 0x$&," /t "|" /f test.txt /o -

or

call jrepl ".." "$txt=($off==0?'0x':' 0x')+$0+','" /jq /f test.txt /o - 
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Thank you, just missing the comma at the end of each line, but it's perfect! With echo 0x!ln!, works great! – Estudiante Feb 14 '17 at 09:26
  • @Estudiante - I never dreamed you would want a comma at the end, and I never scrolled your result to see it. I fixed all my answers to add the trailing comma. – dbenham Feb 14 '17 at 12:28
0

Here is another pure solution, using goto loops:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=%~1"

< "%_FILE%" > "%_FILE%.new" call :READ
> nul move /Y "%_FILE%.new" "%_FILE%"

endlocal
exit /B


:READ
    rem // Read one line, stop if empty:
    set "LINE="
    set /P LINE=""
    if not defined LINE goto :EOF
    set "BUF="
:LOOP
    rem // Process line, build new one:
    set "HEX=%LINE:~,2%"
    set "BUF=%BUF%0x%HEX%, "
    if "%LINE:~3%"=="" goto :NEXT
    set "LINE=%LINE:~2%"
    goto :LOOP
:NEXT
    rem // Return built line, read next one:
    echo %BUF:~,-1%
    goto :READ
aschipfl
  • 33,626
  • 12
  • 54
  • 99