0

I need to loop through a list of text files, and rewrite them inserting a part of their name in one of the first lines, like:

Original file name: 101f.htm

Original file content:

Line1
Line2
.
.
LineN

New file name: 101f_.htm

New file content:

<head> 
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
</head> 
<tr> 
Paciente Matricula: 101
</tr> 

Line1
Line2
.
.
LineN

I achieved some result with this .bat script:

set NOME=%%~ni_.xls
set MTR=%%~ni
for /R c:\teste\teste %%i IN (*.htm) DO (
ECHO.^<head^> > %NOME%
ECHO.^<meta http-equiv^="Content-Type" content^="text/html;charset=utf-8"^> >> %NOME%
ECHO.^</head^> >> %NOME%
ECHO.^<tr^> >> %NOME%
ECHO.Paciente Matricula: %MTR% >> %NOME%
ECHO.^</tr^> >> %NOME%
ECHO. >> %NOME%
type %%~nxi >> %NOME%
PAUSE
)

It gives me all I need, except by the line:

"Paciente Matricula: 101f"

I need to remove that "f" to the line display like:

"Paciente Matricula: 101"

Thanks in advance!

2 Answers 2

3

try this code example:

@echo on &setlocal
for /R "c:\teste\teste" %%i IN (*f.htm) DO (
    (
    set "NOME=%%~ni_.xls"
    set "MTR=%%~ni"
    setlocal enabledelayedexpansion
    ECHO(^<head^> 
    ECHO(^<meta http-equiv="Content-Type" content="text/html;charset=utf-8"^>
    ECHO(^</head^>
    ECHO(^<tr^>
    ECHO(Paciente Matricula: !MTR:~0,-1!
    ECHO(^</tr^>
    ECHO(
    type "%%~nxi"
    )>"!NOME!"
    endlocal
)

Inside a codeblock (in the for loop from the first to the last parenthesis) you can't access % variables with changing values (%NOME%), there you must use delayed expansion and ! variables (!NOME!).

Sign up to request clarification or add additional context in comments.

1 Comment

Using setlocal enabledelayedexpansion and !MTR! solved the problem!
0

Based on Endoro's answer, using the following replace syntax works:

set MTR=%%~ni
set MTR=!MTR:f=!

I used this sintax because the I can not grant the "f" character will be the last one, it can be followed by a space.

The script below works for the task.

setlocal ENABLEDELAYEDEXPANSION
set NOME=%%~ni_.xls
for /R c:\teste\teste %%i IN (*.htm) DO (
set MTR=%%~ni
set MTR=!MTR:f=!
ECHO.^<head^> > %NOME%
ECHO.^<meta http-equiv^="Content-Type" content^="text/html;charset=utf-8"^> >> %NOME%
ECHO.^</head^> >> %NOME%
ECHO.^<tr^> >> %NOME%
ECHO.Paciente Matricula: !MTR! >> %NOME%
ECHO.^</tr^> >> %NOME%
ECHO. >> %NOME%
type %%~nxi >> %NOME%
)

1 Comment

You should use Endoro's way to use a block for the output and redirect the complete block only once to a file, as your way will append to each line a space

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.