Windows bat поиск в файле

Rob van der Woude's Scripting Pages

Use the FIND command to search for a specific string in a file or files and send the specified lines to your output device.

(you may prefer FINDSTR, a much more powerful version of FIND, which even supports regular expressions.)

    Syntax:
   
  FIND [/V or /C][/I][/N] «string» [drive:][path]filename
  where:
  /V Displays all lines not containing the string specified.
  /C Displays the count of lines containing the string.
  /I Ignores the case of characters when searching for the string.
  /N Displays the line numbers with the displayed lines.
  /OFF[LINE] Do not skip files with offline attribute set (only available in Windows XP and later versions).
  «string» Specifies the text string to find.
  drive:\path   Specifies the location of the file or files to search.
  filename Specifies the name of the file to be searched.
 
  If a path is not specified, FIND searches the text typed at the prompt or piped from another command.
Note: If the "string" contains any «special» characters (i.e. doublequote, ampersand, pipe, greater or less than, caret, percent sign) these characters need to be escaped: a literal percent sign must be replaced by a double percent sign, a literal doublequote by 2 doublequotes, the rest must be preceded by a caret.
If the FIND command is placed within a code block (i.e. in parenthesis) it is safest to escape parenthesis inside the text string with carets too.

So, with /C, FIND may be used for counting as well.

Use the FIND command to check if your HTML files have a closing tag for each opening tag:

C:\>FIND /C /I "<TD" example.html

---------- example.html: 20

C:\>FIND /C /I "</TD" example.html

---------- example.html: 20

C:\>_

Combine it with FOR to create this small batch file (for Windows NT or later, or OS/2), which should be called with an HTML file name as its only argument:

@ECHO OFF
FOR %%A IN (A CODE FONT H1 H2 H3 P PRE TABLE TD TH TR) DO (
	ECHO.%%A
	FIND /C /I "<%%A" %1
	ECHO./%%A
	FIND /C /I "</%%A" %1
)
Notes: 1: In this example FIND /C will only display the number of lines it finds with the search string specified; it does not display the number of occurrences of the search string!
2: In «true» DOS batch files, no line should ever exceed 127 characters.

FIND returns an errorlevel 1 if the search string wasn’t found (as of MS-DOS 6).
IsDev.bat is an example of a batch file depending on this feature.

Credits

Thanks to Robert Cruz, who provided me with details on escaping doublequotes in FIND‘s search string.
He also provided this link to Microsoft’s FIND command web page.


page last modified: 2016-09-19; loaded in 0.0037 seconds

Batch files are a powerful tool for automating repetitive tasks on Windows systems. When dealing with text files, finding specific information is often crucial for processing or manipulating data. In this article, we’ll explore how to use the FIND and FINDSTR commands in batch files to search for text within files. Additionally, we’ll demonstrate how to automate certain tasks based on the search results.

  • Using the FIND Command:

The FIND command is a simple yet effective way to search for a specific string in a text file. The basic syntax of the FIND command is as follows:

FIND "search_string" "file_path"

Example: Suppose we have a file named “data.txt” with the following content:

apples
bananas
oranges
grapes

Now, let’s create a batch file named “find_fruits.bat” to find the word “bananas” in the “data.txt” file:

@echo off
set search_string=bananas
set file_path=data.txt

FIND "%search_string%" "%file_path%"
if %errorlevel% equ 0 (
    echo Found %search_string% in %file_path%
) else (
    echo %search_string% not found in %file_path%
)

Running the batch file will output:

Found bananas in data.txt
  • Using the FINDSTR Command:

The FINDSTR command is a more advanced text search tool that supports regular expressions, multiple search strings, and more options compared to FIND. Its syntax is as follows:

FINDSTR ["/C:string"] ["search_string"] [file_path(s)]

Example: Let’s modify our previous example to use FINDSTR instead, and we’ll also add regular expression support. We want to find any lines in “data.txt” containing either “apples” or “oranges”:

@echo off
set search_string=apples oranges
set file_path=data.txt

FINDSTR /C:"%search_string%" "%file_path%"
if %errorlevel% equ 0 (
    echo Found %search_string% in %file_path%
) else (
    echo %search_string% not found in %file_path%
)

Running the batch file will output:

apples
oranges
Found apples oranges in data.txt
  • Automating Tasks based on Search Results:

Now, let’s enhance our batch file to perform different actions based on the search results. In this example, we’ll create a batch file named “fruit_task.bat” that looks for the word “grapes” in “data.txt” and performs an action accordingly:

@echo off
set search_string=grapes
set file_path=data.txt

FIND "%search_string%" "%file_path%" > nul
if %errorlevel% equ 0 (
    echo Found %search_string% in %file_path%
    REM Insert your desired action here
) else (
    echo %search_string% not found in %file_path%
    REM Insert another action if needed
)

In this script, we used > nul to suppress the FIND command’s output and only check the error level to determine if the search string was found or not.

Limitations

The FIND command, while useful for basic text searching in batch files, does have some limitations that you should be aware of:

  1. Exact String Match: The FIND command performs an exact match of the specified search string. It cannot perform partial matches or use regular expressions, which limits its flexibility in certain scenarios.
  2. Case Sensitivity: By default, FIND is case sensitive, meaning it will only match text with the exact same casing as the search string. This can lead to missed results if the case does not match.
  3. No Regular Expression Support: Unlike the more advanced FINDSTR command, FIND does not support regular expressions. This makes it less powerful for complex search patterns.
  4. Single File Search: The FIND command can only search for text within a single file at a time. If you need to search multiple files simultaneously, you have to use a loop in the batch file to iterate through the files.
  5. No Line Numbers: FIND does not provide line numbers for the matches it finds in the file. This makes it challenging to locate the exact position of the match within the file.
  6. Error Level: FIND returns an error level of 0 if it finds the search string and 1 if it does not. While this can be useful for basic conditional checks, it doesn’t provide additional information about the search results.

Given these limitations, if you require more advanced text searching capabilities or need to work with multiple files, you should consider using the FINDSTR command instead. FINDSTR overcomes most of these limitations by offering regular expression support, case-insensitive searches, multi-file search, and line number display.

In summary, while FIND is handy for simple text searches within a single file in a batch file, it may not be the best choice for more complex or versatile search requirements. For those cases, FINDSTR is the more powerful and flexible option.

On the other hand although FINDSTR is a more powerful text searching tool compared to FIND, it also has some limitations that you should be aware of:

  1. Regular Expression Complexity: While FINDSTR supports regular expressions, it has a more limited regex syntax compared to some other text processing tools. It may not support all the advanced regex features that you might find in dedicated regex engines or tools.
  2. Limited Line Length: FINDSTR has a maximum line length it can handle, typically around 8,191 characters. If you attempt to search for a pattern in a very long line, the search may fail or produce unexpected results.
  3. Encoding Support: FINDSTR is primarily designed to work with ASCII text files. It may not handle certain Unicode encodings or other character encodings correctly.
  4. Limited to Text Files: FINDSTR is suitable for searching text files but may not work as expected with binary files or files in non-standard formats.
  5. Slower for Large Files: When dealing with very large files, FINDSTR might be slower compared to other specialized search tools designed for handling massive datasets efficiently.
  6. No Recursive Search: Unlike some other search tools, FINDSTR does not have a built-in option for recursively searching through subdirectories. If you need to search through multiple levels of directories, you’ll need to use other commands (e.g., FOR) in conjunction with FINDSTR.
  7. Limited Context Display: FINDSTR allows you to display lines containing the search pattern but provides limited control over the number of lines shown before and after the match. This might be insufficient for certain context-based searches.
  8. Output Formatting: FINDSTR outputs matching lines by default, but it might not be easy to customize the output format. You may need to use additional commands to further process the output as needed.

Despite these limitations, FINDSTR remains a valuable tool for searching and filtering text in batch files and the Windows command prompt. It is especially useful for simple and intermediate text search requirements where regular expressions and basic filtering options are sufficient.

If you encounter scenarios where FINDSTR’s limitations become a hindrance, you may need to consider using more advanced text processing tools, scripting languages, or specialized search utilities to meet your specific needs. Each tool has its strengths and weaknesses, so choosing the right one depends on the complexity and scale of your text search tasks.

Conclusion

Batch files are incredibly useful for automating tasks on Windows systems, and text searching is a common operation. By using the FIND and FINDSTR commands in batch files, you can efficiently search for text within files and trigger different actions based on the search results. Whether it’s a simple search using FIND or a more advanced search with FINDSTR and regular expressions, batch files offer a flexible and straightforward solution to streamline your automation processes.

JCGs (Java Code Geeks) is an independent online community focused on creating the ultimate Java to Java developers resource center; targeted at the technical architect, technical team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects.

Приветствую, уважаемые участники проекта Habrahabr. Сегодня я хочу рассказать вам как выполнить поиск файлов в интерпретаторе командной строки Windows — cmd.exe. Я не буду вам писать такую команду, как dir или find. Мы сегодня рассмотрим другой, более лучший способ.

Давайте представим такую ситуацию: «Вы начинающий программист, и вам стоит задача: Сделать импорт всех (или некоторых файлов) из определенного каталога. Причем, чтобы можно было искать любые файлы, с любым названием и расширением. При этом импорт должен быть помещен в один файл. С сохранением всех путей файлов, построчно».

Вот как будет выглядеть данный код:

@Echo Off & Title Seacher File
Echo Status oparations: In Progress...
For /R D:\ %%i In (*.doc) Do (
 	If Exist %%i (
		Echo %%i >> D:\Resault.doc
	)
)
Cls & Echo Status Oparations: Ended Seacher
Pause & Start D:\Resault.doc & Echo On

А теперь, давайте разберем, что он делает!

Первая строка кода:

@Echo Off & Title Seacher File

Скрывает все происходящее в командном файле, и параллельно меняет заголовок командной строки.

Вторая строка кода:

Echo Status oparations: In Progress...

Выводит статус операции.

Третья строка кода:

For /R D:\ %%i In (*.doc) Do (

Иницилизация цикла For.

Четвертая строка кода:

If Exist %%i (

Иницилизация цикла If.

Пятая строка кода:

Echo %%i >> D:\Resault.doc

Условие если файл найден.

Восьмая строка кода:

Cls & Echo Status Oparations: Ended Seacher

Очистка крана, и вывод конечного сообщения об окончании операции.

Девятая строка кода:

Pause & Start D:\Resault.doc & Echo On

Пауза, перед закрытием пакетного файла и запуск файла с результатами.

Выводы

Данный bat файл, универсален, удобен в использовании, но есть одно, НО!

Условия поиска нужно вводить вручную, и путь где искать

Чем асинхронная логика (схемотехника) лучше тактируемой, как я думаю, что помимо энергоэффективности — ещё и безопасность.

Hrethgir 14.05.2025

Помимо огромного плюса в энергоэффективности, асинхронная логика — тотальный контроль над каждым совершённым тактом, а значит — безусловная безопасность, где безконтрольно не совершится ни одного. . .

Многопоточные приложения на C++

bytestream 14.05.2025

C++ всегда был языком, тесно работающим с железом, и потому особеннно эффективным для многопоточного программирования. Стандарт C++11 произвёл революцию, добавив в язык нативную поддержку потоков,. . .

Stack, Queue и Hashtable в C#

UnmanagedCoder 14.05.2025

Каждый опытный разработчик наверняка сталкивался с ситуацией, когда невинный на первый взгляд List<T> превращался в узкое горлышко всего приложения. Причина проста: универсальность – это прекрасно,. . .

Как использовать OAuth2 со Spring Security в Java

Javaican 14.05.2025

Протокол OAuth2 часто путают с механизмами аутентификации, хотя по сути это протокол авторизации. Представьте, что вместо передачи ключей от всего дома вашему другу, который пришёл полить цветы, вы. . .

Анализ текста на Python с NLTK и Spacy

AI_Generated 14.05.2025

NLTK, старожил в мире обработки естественного языка на Python, содержит богатейшую коллекцию алгоритмов и готовых моделей. Эта библиотека отлично подходит для образовательных целей и. . .

Реализация DI в PHP

Jason-Webb 13.05.2025

Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .

Обработка изображений в реальном времени на C# с OpenCV

stackOverflow 13.05.2025

Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 11 build 21380
  • Полный русификатор для windows xp
  • Windows 10 не выключается через меню пуск
  • Internal error 0x0a protection initialization failed как исправить windows 10
  • Почему не начинается установка windows 10 с флешки