FINDSTR-在最后一个字符串匹配时停止 [英] FINDSTR - Stop on last string match

查看:53
本文介绍了FINDSTR-在最后一个字符串匹配时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一百个文本文件,试图提取包含foobar的行,但是这些文本文件也包含多组重复项.

I have a hundred text files where I am trying to extract lines containing the word foobar, but the text files also contain multiple sets of duplicates.

我有这个,很明显,它会吐出每行包含foobar的行,该行可以工作,但是会产生带有重复项的文件

I have this, which obviously spits each line containing foobar, which works but produces the file with duplicates

findstr /C:"foobar" test.txt  > result.txt

例如

test.txt包含

test.txt contains

foobar 

foobar 

foorbar            ##

然后在文本文件中进一步重复该操作,如何使它停止在"foobar ##"(其中##代表整数)并随后删除所有内容?

Then this repeats further down the text file, how could I get it to just stop on "foobar ##" where ## represents an integer and delete everything thereafter?

我尝试过,但是cmd窗口挂起,不确定是什么.

I tried this, but the cmd window hangs, not sure on what.

@echo off


findstr /b /C:"foobar" test.txt  > results

SET STOPSTR="foobar              ##"
for /f %%a in (results) do (

FINDSTR /c:"foobar" > newresults
IF %%a==%STOPSTR% GOTO END

)
:END
exit

推荐答案

(
for /f "delims=" %%a in (results) do (

 IF "%%a"=="%STOPSTR%" GOTO END
 echo %%a
)
)>newresults

请注意,多余的一对括号用于将 echo 输出重定向到文件.

Note that the extra pair of parentheses acts to redirect the echo output to the file.

如果要保留包含终止字符串的行,请反转 if echo 行.

If you want to retain the line containing your stopstring, reverse the if and echo lines.

if 中的元素需要用引号引起来,因为它们(可能)包含分隔符(如空格)

The elements in the if need to be quoted since they (may) contain separators (like spaces)

"delims =" 确保将整个行分配给 %% a ,否则仅分配第一个以空格分隔的令牌(有关详细信息,请参见/?提示输入docco)

The "delims=" ensures that the entire line is assigned to %%a otherwise just the first space-delimited token will be assigned (see for/? from the prompt for docco)

这篇关于FINDSTR-在最后一个字符串匹配时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆