首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >批量从txt中剪切大括号中的文本

批量从txt中剪切大括号中的文本
EN

Stack Overflow用户
提问于 2017-06-27 14:17:19
回答 2查看 94关注 0票数 0

我有很多.txt文件,其中包含这样的信息:

randomtextIMPORTANTTEXTmorerandomtext

如何在没有大括号的情况下删除重要的文本,并可能批量覆盖原始的.txt?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-29 01:29:55

下面还将在同一行中执行多个实例。我将让您将其更改为使用*.txt文件的路径。

测试数据:

代码语言:javascript
复制
Test1.txt
randomtext[IMPORTANTTEXT1a]morerandomtext
randomtext[IMPORTANTTEXT1b]morerandomtext

Test2.txt
randomtext[IMPORTANTTEXT2]morerandomtext
randomtext[IMPORTANTTEXT2a]morerandomtext randomtext[IMPORTANTTEXT2b]morerandomtext

批处理文件:

代码语言:javascript
复制
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

rem For each text file in the current directory...
for /f "tokens=*" %%F in ('dir /b *.txt') do (
    set FileSpec=%%F

    rem For each line of text in the file that has at least one [ 
    for /f "tokens=1,* delims=[" %%a in (!FileSpec!) do (
        rem This line of text has a [ so get the important text. %%a[%%b
        rem below passes the entire line of text.
        call :FindImportantText %%a[%%b
    )
)
ENDLOCAL
pause
exit /b

:FindImportantText
for /f "tokens=1,* delims=[" %%c in ("%*") do (
    rem The "%*" above is the entire line of text even if it contains
    rem spaces which would normally delimit the line into pieces
    if not "%%d"=="" (
        rem There is a [ and text following the [. %%d is the portion
        rem following the [.

        rem so find the ending ]
        for /f "tokens=1,* delims=]" %%e in ("%%d") do (
            if not "%%f"=="" (
                rem We have an ending ] so show it
                echo ImportantText in !FileSpec!=%%e

                rem Try again with the remaining portion of the line
                call :FindImportantText %%f         
            )
        )
    ) 
)
exit /b
票数 0
EN

Stack Overflow用户

发布于 2017-06-27 19:20:40

这将过滤掉第一对括号之间的部分:

代码语言:javascript
复制
for /f "tokens=2 delims=[]" %%a in ('type %1') do echo.%%a>>%2

如果有没有任何“重要部件”的行,可以用findstr跳过它们,或者检查输出是否为空:

代码语言:javascript
复制
for /f "tokens=2 delims=[]" %%a in ('type %1') do if "%%a" neq "" echo.%%a>>%2

若要处理当前目录中的所有.txt文件,请使用另一个循环调用循环:

代码语言:javascript
复制
@echo off
for %%a in (*.txt) do call :brekkies "%%a" "%%~na_out.txt"&echo.%%a
echo.done.
exit /b

:brekkies
for /f "tokens=2 delims=[]" %%a in ('type %1') do if "%%a" neq "" echo.%%a>>%2

文件将被命名为"name_out.txt“。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44782652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档