2017-06-27 32 views
0

にTXTから括弧内のテキストをカット私はこのような情報を持っている.txtファイルがたくさんあります元の.txtをバッチで上書きしますか?バッチ

+3

は '['/']'(四角)括弧であり、 '{'/'}'通常ブレースと呼ばれます。とにかく、自分で何か試しましたか?これまで[for/F'コマンド](http://ss64.com/nt/for_f.html)について聞いたことがありますか? – aschipfl

+0

はい、私はいくつかのことを試して、答えを見つけようとしましたが、私は本当にバッチに精通していません。区切り文字を理解できず、ループ内でテキストをナビゲートする方法を理解していません。 –

+1

同じ行に複数の「重要な部分」がありますか? – Regejok

答えて

0

次の例でも、同じ行に複数のインスタンスを作成します。 * .txtファイルのパスを使用するように変更しておきます。

試験データ:

Test1.txt 
randomtext[IMPORTANTTEXT1a]morerandomtext 
randomtext[IMPORTANTTEXT1b]morerandomtext 

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

バッチファイル:

@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

これは括弧の最初のペアの間の部分を除外します:

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

任意の「重要な部分」のない行がある場合、あなたはfindstrまたは出力が空であるかどうかをチェックすることによって、それらをスキップすることができます。

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

別のループでループを呼び出し、現在のディレクトリ内のすべての.txtファイルを処理するには:

@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"となります。

+1

トークンが1つだけの場合(2)、 '%% b'はありません。ちょうど' %% a' ... – Stephan

+0

@Stephan @Stephanはすばやく編集されました。 – Regejok