批处理文件以读取文本文件并搜索字符串。如果找到字符串,则返回错误代码1

时间:2018-12-19 10:50:08

标签: batch-file

我想读取一个文本文件并在该文本文件内找到一个字符串。 如果存在搜索字符串,则需要使用errorcode 1退出批处理。

示例:

Text inside a txt file would be like (123;345;678;abc)
i need to search the string / numeric value (abc or 123)

如果找到,则批处理应返回1。

2 个答案:

答案 0 :(得分:0)

According to find, you should be able to perform it like this:

find "myTextToSearch" C:\\Path\\To\\File.txt

But, like you can see in documentation, these are the exit status:

Errorlevel

FIND will return an ErrorLevel as follows:

0 String found in at least one of the files.

1 String not found

2 If any files in the list do not exist or if no files match a wildcard mask.

An invalid switch is given.

So either you should consider 0 (matching OK), instead of 1, either you should add post instruction to convert the status like you want.

Let me know if you need further information.

答案 1 :(得分:0)

如果文本文件包含abc和/或123,然后以1退出,对吗?

findstr "abc 123" file.txt && (exit /b 1) || (exit /b 0)

findstr返回0(如果找到了字符串(“成功”),则返回1(如果没有找到字符串(“ Fail”))(与您完全一样)需要它)。如果您可以将0用于“找到”,将1用于“找不到”:

findstr "abc 123" file.txt
exit /b %errorlevel%