批处理文件,如何删除文本文件中的第一个单词,只在第一行中删除?

时间:2016-05-17 07:15:46

标签: string batch-file text cut

我有一个.txt文件,可能在各行上包含各种单词,我只想删除第一行中的第一个单词。 (例如:我的文本文件中有2行,每行包含2个单词(第一行为abc,bcd,第二行为bde,第二行为def),我希望第一行输出为bcd,第二行为cde,def为第二行)。我研究了这个,我只是想到了如何删除所有行中的第一个单词,但我只需要在第一行。提前谢谢。

这是我能找到的最接近的答案,但它删除了所有行中的第一个单词,我只需要第一行。 Remove First Word in text stream

1 个答案:

答案 0 :(得分:1)

虽然你没有向我们展示你自己在解决问题上的努力,但我决定提供一些代码,因为这项任务对我来说似乎并不是特别微不足道......

下面的脚本会删除第一行中的第一个单词。

以下内容使用for /F循环读取给定的文本文件,并通过另一个嵌套的for /F循环拆分第一行中的第一个单词;其余的行未经编辑返回:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

set "FLAG=" & rem // (this marks the first line)
for /F "delims=" %%L in ('findstr /N /R "^" "%~1"') do (
    set "LINE=%%L"
    rem // (toggle delayed expansion to not lose `!`)
    setlocal EnableDelayedExpansion
    if defined FLAG (
        rem // (this is executed for all but the first lines)
        echo(!LINE:*:=!
    ) else (
        rem // (this is executed for the first line only)
        for /F "tokens=1,*" %%E in ("!LINE!") do (
            endlocal
            rem // (return line with first word removed)
            echo(%%F
            setlocal EnableDelayedExpansion
        )
    )
    endlocal
    rem // (set this after the first loop iteration)
    set "FLAG=#"
)

endlocal
exit /B

这个通过重定向读取给定的文本文件,再次通过for /F循环拆分第一行的第一个单词,并通过findstr命令行返回剩余的行:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

< "%~1" (
    rem // (capture first line here)
    set /P "LINE="
    rem // (toggle delayed expansion to not lose `!`)
    setlocal EnableDelayedExpansion
    rem // (this is executed for the first line only)
    for /F "tokens=1,*" %%I in ('echo^(!LINE!^| findstr /N /R "^^"') do (
        endlocal
        rem // (return line with first word removed)
        echo(%%J
        setlocal EnableDelayedExpansion
    )
    endlocal
    rem // (this is executed for all but the first lines)
    findstr /R "^"
)

endlocal
exit /B

两个脚本都希望输入文本文件作为命令行参数提供。假设任一脚本存储为remove-first-word.bat且文本文件名为sample.txt,则使用的命令行如下:

remove-first-word.bat "sample.txt"

或:

remove-first-word.bat "\path\to\sample.txt"

要将输出写入另一个文件,比如return.txt,而不是控制台,请使用重定向:

remove-first-word.bat "sample.txt" > "return.txt"

或:

remove-first-word.bat "\path\to\sample.txt" > "\path\to\return.txt"
相关问题