1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

batのfindstrの正規表現で「()」や「|」や「{}」が使えねぇじゃねーか!!(and条件or条件!)

Last updated at Posted at 2023-12-04

はじめに:sunny:

batのfindstrを使って正規表現で、特定の条件下のデータだけ、抽出というもの。
備忘として記事に残しておこうと思う。(だいぶ悩んだ・・・)

こんな感じ:sunny:

:one:通常バージョン

findstrはこんな感じで使っていた

for /f "tokens=1-10* delims=," %%a in (%file_path%) do (
    @echo %%a|findstr /r /c:"正規表現" > nul
)

:two: and条件

条件としては、
正規表現A
かつ
正規表現B

の条件に合致するもの。

for /f "tokens=1-10* delims=," %%a in (%file_path%) do (
    echo %%a | findstr /r /c:"正規表現A" > nul && echo %%a | findstr /r /c:"正規表現B" > nul
)

:three: or条件

条件としては、
正規表現A
または、
正規表現B

の条件に合致するもの。

「||」はエラーレベルが0以外の場合に、後続のコマンドが実行されるというものです。
正規表現Aかつ正規表現Bの正規表現で見つからなかった場合、(ここで見つからなかった場合エラーレベルで「1」が返される。見つかった場合には「0」)
後続のset flg=trueのコマンドが実行される。というものです。

for /f "tokens=1-10* delims=," %%a in (%file_path%) do (
    @echo %%a|findstr /r /c:"正規表現A" > nul || set flg=true
    @echo %%a|findstr /r /c:"正規表現B" > nul || set flg=true
    if flg==true echo どちらかの条件に一致

終わりに:sunny:

batのfindstrの正規表現は使える正規表現の種類が少なくて参っちまうぜ・・・。
(PythonとかPowerShellでいいじゃん!とは、思っていたり思っていなかったり・・・笑)
普通ならもっと短くかけるのに~
短いですが、ほいじゃ:raised_hands:

参考

2024/01/05 間違っていたため大幅に修正しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?