求批处理 提取文本中每行最末尾的中括号及其内部字符

求大神动动手指啊。
我有几百万行格式基本固定的文本如下,每行末尾一定是一个中括号及内部字符。但是行中也可能出现中括号,现在我提取每行末尾那个中括号及其内部字符,行中中括号不要。
求大神写个批处理
> CT_875 [Chlamydia trachomatis D/UW-3/CX]
> superantigen-like protein [Staphylococcus aureus subsp. aureus str. Newman]
> tryptophanyl-tRNA [synthetase] [Salmonella enterica subsp. enterica serovar Agona str. SL483]
> AsnC [family transcriptional] regulator [Geodermatophilus obscurus DSM 43160]
> methionyl-tRNA formyltransferase [[Clostridium] saccharolyticum WM1]

把下面的myfile=后面的内容,换成你自己的文件名。 bat的输出是直接在屏幕上,你可以按:

c:\>get_str.bat >> output.txt

这种方式运行。

@echo off & setlocal enabledelayedexpansion

set "myfile=data.txt"
for /f "delims=" %%a in (%myfile%) do (
  call :extract_sub_string "%%a"
)
goto end

:extract_sub_string
set "ts=%~1"
set newstr=
set /a pos=-2
set "sflag=0"
set "chr="
:loop
for %%i in ("!pos!") do set chr=!ts:~%%~i,1!
if '!chr!'==']' set sflag=1
if '!chr!'=='[' set sflag=1
if !sflag! equ 0 (
  set /a pos-=1
  set newstr=!chr!!newstr!
  goto loop
)
for /f "tokens=* delims= " %%a in ('echo !newstr!') do set newstr=%%a
echo !newstr!
goto:eof


:end
endlocal & @echo on

按你上面的测试数据,运用结果如下:

Chlamydia trachomatis D/UW-3/CX
Staphylococcus aureus subsp. aureus str. Newman
Salmonella enterica subsp. enterica serovar Agona str. SL483
Geodermatophilus obscurus DSM 43160
saccharolyticum WM1

温馨提示:答案为网友推荐,仅供参考
相似回答