【问题标题】:Copying the last paragraph in a text file复制文本文件中的最后一段
【发布时间】:2016-03-20 12:04:46
【问题描述】:

我有兴趣编写一个批处理脚本,它将最终文本块复制到一个包含许多其他文本块的 .txt 文件中。想想脚本执行的日志文件,但没有任何一致的内容或长度。每个条目由一个空行分隔。

所以对于下面的文档,我只想选择并复制最后一段:

Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Exceptioneur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum。

文本本身的长度可能不同。我需要的唯一可靠指标是文档中最后一个空白行之后的所有内容——在这种情况下,“Duis aute...”之后的所有内容

我认为脚本的大纲会是这样的,但我对批处理一点也不熟悉。非常感谢您提供的任何帮助!

SET FOO
FOR /F "delims=" %%G IN (somefile.txt) DO
(IF "%%G"=="" (SET FOO="" )
ELSE (SET FOO==%%G + %FOO%))
ECHO %FOO%>whatever.txt

【问题讨论】:

    标签: batch-file text


    【解决方案1】:
    @echo off
    setlocal
    
    rem Get the line number of the last empty line
    for /F "delims=:" %%a in ('findstr /N "^$" somefile.txt') do set "skip=skip=%%a"
    
    rem Show all lines after it
    for /F "%skip% delims=" %%a in (somefile.txt) do echo %%a
    

    【讨论】:

    • 非常酷——谢谢!奇怪的是,在我一直在玩的一些文本文件中,我似乎只抓住了最后一行文本。在这些文件中,第一个“for”传递正确的最后一个空行,但随后的“for”循环只回显最后一行。
    • 没关系——我没有正确引导输出。效果很好——谢谢!
    • 我可以请您选择并赞成这个答案吗?谢谢!
    • 优雅的解决方案,@Aacini,+1!当somefile.txt 不包含任何空行(skip= 不能为空)时,我修复了一个小问题...
    【解决方案2】:

    你可以这样做:

    @echo off
    setlocal EnableDelayedExpansion
    SET "FOO="
    type "file.txt" > "file.txt.tmp"
    for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "file.txt.tmp"') do if [%%B]==[] (SET "FOO=") else (SET "FOO=!FOO!%%B")
    del "file.txt.tmp"
    >filepara.txt echo %FOO%
    

    这只有一个缺点,它不会将原始段落的换行符回显到文本文件中。

    编辑:

    我找到了一种方法来保留换行符,方法是创建一个包含换行符的变量:

    @echo off
    setlocal EnableDelayedExpansion
    set LF=^
    
    
    SET "FOO="
    type "file.txt" > "file.txt.tmp"
    for /f "tokens=1* delims=:" eol=¬ %%A in ('findstr /n "^" "file.txt.tmp"') do if [%%B]==[] (SET "FOO=") else (SET "FOO=!FOO!%%B!LF!")
    del "file.txt.tmp"
    >temp.txt echo !FOO!
    more temp.txt > paragraph.txt
    del temp.txt
    

    注意:你需要设置 LF 之后的两个空行才能工作!

    【讨论】:

    • 谢谢!这是解决换行问题的另一种不太优雅的方法: for /f "tokens=1* delims=:" %%A in ('findstr /n "^" "file.txt.tmp"') do if [% %B]==[] (echo.> tmp.out) else (echo %%B >> tmp.out) del "file.txt.tmp" move tmp.out test2.txt
    • 但是出现了一个问题:如果文本中有分号怎么办?有没有办法解决这个问题?
    • 您可以将 eol 设置为未使用的字符,明天会更新我的答案
    猜你喜欢
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多