使用批处理文件将txt转换为HTML

时间:2013-05-30 16:37:30

标签: html parsing batch-file contains

我有简单的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)
)

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

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

1 个答案:

答案 0 :(得分: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将enabledelayedexpansion添加到setlocal和echo!行!之后:rawout以适应不平衡报价}