1

我有普通的txt文件,例如:

===
Date:30.05.2013
**Header**
text

===
Date:29.05.2013
**Header**
text

===
etc.

我想将其转换为 html 文件,如:

<hr>
<b>Date:30.05.2013</b>
<h1>Header</h1>
text
<br>
<hr>
<b>Date:29.05.2013</b>
<h1>Header</h1>
text
<br>
<hr>
etc.

我知道“for”命令,我使用它

for /f "tokens=*" %%f in ('type news.txt') do (
if [%%f]==[===] (echo ^<hr/^> >>news.htm) ELSE (echo %%f^<br/^> >>news.htm)
)

但我不知道,如何对包含关键字(例如 Date 或 *)的字符串执行其他操作,也不知道如何在文本文件中为空白字符串插入空白 br 标签。

请帮帮我,我花了很多时间=(

4

1 回答 1

2
@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "br=^<br^>"
SET "hr=^<hr^>"
SET "h1=^<h1^>"
SET "sh1=^</h1^>"
SET "bold=^<b^>"
SET "sbold=^</b^>"

(
FOR /f "delims=" %%i IN ('type news.txt^|findstr /n "$"') DO (
SET line=%%i&CALL :process
)
)>news.html

GOTO :eof

:process
:: remove line number from line
SET "line=%line:*:=%"
IF NOT DEFINED line ECHO(%br%&GOTO :EOF
SET "line2=%line:"=_%"
SET "line3=%line:"=%"
IF NOT "%line2%"=="%line3%" GOTO rawout
IF "%line%"=="==="  ECHO(%hr%&GOTO :EOF
IF "%line:~0,5%"=="Date:"  ECHO(%bold%%line%%sbold%&GOTO :EOF
IF "%line:~0,2%%line:~-2%"=="****" ECHO(%h1%%line:~2,-2%%sh1%&GOTO :EOF
:rawout
ECHO(!line!%br%
GOTO :eof

这应该适合你。它对每一行进行编号,然后将编号的行分配给line. 这是一种常用技术,因为for /f会跳过空行。

:process仅查找密钥字符串并输出适当的替换。

我使用了检测“开始和结束”的快捷方式“**” . There are more reliable ways of doing it - but it should only fail if the line is*** or**` - 如果有问题,相对容易修复......

(编辑 20130531-0134Z 新:process程序以更改规范)

{重新编辑 20130531-0750Z 将 enableelayedexpansion 添加到 setlocal 和 echo !line!在 :rawout 之后以适应不平衡引号}

于 2013-05-30T17:24:44.833 回答