如何删除第一个单词后的所有内容?

时间:2017-09-29 03:57:51

标签: string file batch-file text

我想删除此文本文档每行中第一个单词后的所有内容。它适用于简单的字符删除,但当我尝试删除“|”时不起作用文本文件。

enter image description here

我正在尝试使用以下代码:

setlocal enableextensions disabledelayedexpansion

set /p txtfile=Text File Name: 
    Echo.
set /p "search=Search for: "
    Echo.
set /p "replace=Replace to: "

    for /f "delims=" %%i in ('type "%txtfile%.txt" ^& break ^> "%txtfile%.txt" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%txtfile%.tmp" echo(!line:%search%=%replace%!
        endlocal
    )

    ren "%txtfile%".tmp "%txtfile%".txt 

pause

但出现以下错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

问题是由于变量|的立即扩展而试图执行的管道字符%search%

可能的解决方法是使用允许引号的临时变量赋值(set "line=..."),因此不再识别管道,然后在echo命令中仅使用延迟扩展线 - 像这样:

setlocal EnableExtensions DisableDelayedExpansion

set /P txtfile="Text File Name: "
echo/
set /P search="Search for: "
echo/
set /P replace="Replace to: "

for /F "delims=" %%i in ('type "%txtfile%.txt" ^& break ^> "%txtfile%.txt"') do (
    set "line=%%i"
    setlocal EnableDelayedExpansion
    set "line=!line:%search%=%replace%!"
    >>"%txtfile%.txt" echo(!line!
    endlocal
)

pause
endlocal

另一种解决方案是对!search!!replace!使用延迟扩展;为了使其工作,你不能直接嵌套延迟扩展,所以你需要使用for /F循环来进行嵌套 - 像这样:

setlocal EnableExtensions DisableDelayedExpansion

set /P txtfile="Text File Name: "
echo/
set /P search="Search for: "
echo/
set /P replace="Replace to: "

for /F "delims=" %%i in ('type "%txtfile%.txt" ^& break ^> "%txtfile%.txt"') do (
    set "line=%%i"
    setlocal EnableDelayedExpansion
    for /F "delims=" %%j in ("!search!=!replace!") do (
        >>"%txtfile%.txt" echo(!line:%%j!
    )
    endlocal
)

pause
endlocal

您可以将整个>>循环重定向到for /F,而不是单独重定向(>)每个输出行,但是您需要使用与该setlocal EnableExtensions DisableDelayedExpansion set /P txtfile="Text File Name: " echo/ set /P search="Search for: " echo/ set /P replace="Replace to: " > "%txtfile%.tmp" ( for /F "usebackq delims=" %%i in ("%txtfile%.txt") do ( set "line=%%i" setlocal EnableDelayedExpansion set "line=!line:%search%=%replace%!" echo(!line! endlocal ) ) move /Y "%txtfile%.tmp" "%txtfile%.txt" > nul pause endlocal 不同的文件你看了 - 看到这个(只显示上面的第一个变种):

.image{
background:red;
}
img{
 width: 100%;
}

这种方法在性能方面要好得多,特别是对于巨大的输入文件。

答案 1 :(得分:0)

在理解了之前的一些代码后,我终于用这段代码解决了问题:

@Echo off

setlocal EnableExtensions DisableDelayedExpansion

set /P txtfile="Text File Name: "
echo/
set /P search="Search for: "
echo/
set /P replace="Replace to: "

for /F "delims=" %%i in ('type "%txtfile%.txt" ^& break ^> %txtfile%.tmp') do (
    set "line=%%i"
    setlocal EnableDelayedExpansion
    set "line=!line:%search%=%replace%!"
    >> %txtfile%.tmp echo(!line!
    endlocal
)

ren %txtfile%.tmp CleanText.txt

pause
endlocal