删除char和CR / LF

时间:2016-12-06 14:15:48

标签: windows batch-file

我有一个文本文件,我需要在特定情况下删除回车/换行符。我不想删除它们。

我知道我可以运行代码来删除CR / LF。但是,我有一个文件,我只希望删除CR / LF,前面是/

看起来像这样(插入正确的位置):

"2016-09-11 23:22:03","20\<CR/LF>
16-09-11 >03:22:24",20160911,1,16,21,281,281,4272,4272,NULL,NULL,NULL,0,2100,2528,NULL<CR/LF>

所以我不想让最后一个删除,只有它前面的\,在上面的第一个例子中。

提前致谢

2 个答案:

答案 0 :(得分:1)

这是一个纯粹的(评论很好的)解决方案 - 假设最终连接的行不超过大约8190个字符或字节:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_FILE=%~1" & rem // (first command line argument specifies the input text file)
set "_CHAR=/"   & rem // (character that marks line concatenation)

rem // Reset buffer for concatenation:
set "CONC="
rem /* Read input text file line by line; since `for /F` ignores empty lines, use `findstr`
rem    to prefix them by their line numbers and a colon, so they do not appear empty: */
for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
    rem // Store current line, including line number prefix:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid loss of exclamation marks:
    setlocal EnableDelayedExpansion
    rem // Check whether last character is the predefined concatenation mark:
    if "!LINE:~-1!"=="%_CHAR%" (
        rem // Contatenation required, so remove line number prefix and concatenate:
        set "LINE=!LINE:*:=!"
        set "CONC=!CONC!!LINE:~,-1!"
    ) else (
        rem /* No concatenation needed, so output current line with line number prefix
        rem    removed and prefixed by current concatenation buffer: */
        echo(!CONC!!LINE:*:=!
        rem // Reset concatenation buffer:
        set "CONC="
    )
    rem /* Transfer concatenation buffer beyond the environment localisation barrier
    rem    (this is needed because of `endlocal` and toggling delayed expansion): */
    for /F "delims=" %%K in (^""!CONC!"^") do (
        endlocal
        set "CONC=%%~K"
    )
)
rem // Output remaining concatenation buffer, if there is something left:
if defined CONC (
    setlocal EnableDelayedExpansion
    echo(!CONC!
    endlocal
)

endlocal
exit /B

这使用/作为标记字符。要将其更改为\,请转到脚本顶部的注释Define constants here:引入的块。

答案 1 :(得分:0)

根据9dan的建议,我通过Notepad ++分三步完成了这项工作。

  1. 通过正则表达式将所有cr / lf更改为Xx
  2. 将\ Xx更改为&#34;&#34; (空白)通过常规
  3. 通过正则表达式将Xx更改为cr / lf
  4. 它按预期工作。

    不确定如何接受9dan的答案,只是想分享。