Windows find text in all files

Поиск текста в файлах через командную строку Windows

Недавно мы рассматривали поиск файлов через командную строку Windows. Сегодня поговорим о том, как найти внутри файлов нужный нам текст. Сделать это можно при помощи команды FIND.

Команда find сообщает имена файлов, в которых был найден искомый файл, и выводит строки, в которых он содержится.

Синтаксис команды find :

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] «искомый_текст» [путь_к_файлу]

V — вывод всех строк, НЕ содержащих искомый текст;

C — вывод только общего числа строк, содержащих искомый текст;

N — вывод номеров строк;

I — поиск без учёта регистра символов;

OFF[LINE] — не пропускать файлы с атрибутом «автономный».

Для примера проверим все текстовые файлы в каталоге C:\test\ на наличие слова «текст».

Если посмотреть на скриншот ниже, то можно подумать, что ни один из файлов не содержит слова «текст». Конечно, это вполне допустимый вариант. Но есть и другое объяснение.

Дело в том, что по умолчанию текст в командной строке Windows отображается согласно кодовой странице CP866, а в файлах он в кодовой странице CP1251. Поэтому нам достаточно сменить кодовую страницу в текущем окне командной строки. О том, как это сделать, можно прочитать в статье по этой ссылке.

Теперь мы видим, что слово «текст» встречается во всех трёх файлах.

Теперь посмотрим на строки, в которых нет слова «текст»:

Такие оказались только в файле FILE_1.TXT.

Помните, что команда find по умолчанию учитывает регистр. Поэтому, написав в ней «Текст», мы не найдём подобного слова в файлах. Но регистр можно и проигнорировать:

На скриншоте ниже хорошо видно, что сперва команда не нашла слова «Текст» в файлах, так как в них оно записано без заглавных букв. Добавив /i , мы это исправили.

Допустим, нам нужно знать порядковые номера строк, в которых отсутствует слово «текст»:

Если мы захотим знать число строк, в которых присутствует искомое слово, тогда выполним команду:

А если нам нужно знать число строк, где это слово отсутствует, тогда пример команды такой:

Хотя до этого в примерах мы искали отдельное слово, find спокойно ищет и выражения:

Особенностью команды find является то, что искомый текст обязательно нужно заключать в кавычки. Это приводит к трудностям, если в пути к файлам (и в именах файлов) содержится пробел. В таком случае нужно воспользоваться перенаправлением ввода, но только если мы ищем в конкретном файле.

Как видите, наличие пробела в имени каталога C:\test test\ не помешало осуществить поиск. Но это что касается поиска в файле file_1.txt. А вот попытка поискать сразу во всех файлах привела к ошибке.

В таком случае можно воспользоваться циклическое обработкой, к примеру, командой for :

Помните, что в этом случае в командной строке нужно использовать конструкции вида %a, а в файлах .bat и .cmd вида %%a.

До этого в примерах мы всегда указывали в каких файлах искать. Если этого не сделать, то команда find выполняет поиск в тексте консоли или в тексте, который был передан по конвейеру другой командой.

Для следующего примера вернём кодовую страницу CP866. После этого отсортируем вывод команды ipconfig /all — оставим только те строки, где содержится слово «Состояние»:

Здесь мы лишь пробежались по вершинам, но возможности команды find гораздо больше. Особенно, если использовать её в комплексе с другими командами.

Find and Replace Text in Multiple Files in Bulk on Windows PC

Sometimes we need to find and replace text in more than one files. The problem begins when we try to do so after opening each file. Certainly, you need only a couple of seconds to find and replace text in two or three files. However, just imagine that you have fifty files and you need to find and replace three words in each file. How do you handle that? Don’t panic. Here is a simple free tool for Windows and this is called Find and Replace Tool. This portable software can find and replace text in multiple files within moments.

Читайте также:  Microsoft windows zip free

Find and Replace Text in Multiple Files

First, download Find and Replace Tool and open it. As this is a portable software, you will not have to install it. After opening Find and Replace Tool, the following screen will appear,

The UI is uncluttered. Therefore, you will understand each and every option very quickly. However, just follow the following steps to find and replace text in multiple files using this free tool.

First, you need to select the Directory, where all the raw files are positioned. It will replace text in those files, which are placed in one folder.

Therefore, to select the directory, just click on the box next to the empty box and choose a directory. After that, write down the particular file extension.

By default, it shows *.*. This means that it will replace text in all files. However, suppose, you want to find and replace text in all .css files. To do so, just enter *.css

If you want to add multiple extensions, add them like this:

On the other hand, if you want to include all files except .exe and similar. To exclude particular extension, just enter the following in the Exclude Mask section,

After that, you need to enter the text in the Find box. You can enter either a single word or a line.

In the next step, write down the text you would like to replace with. After completing all, the window will look like this:

Now, you have two options. First, you can hit the Replace button to replace that text immediately. Second, you can get a command that you need to use through Command Prompt to get the same thing. You will get a command in the Command Use box, and the command looks like this:

Here, C:\Users\Sudip\Downloads\Programs\fnr.exe is the Find and Replace Tool directory and C:\Users\Sudip\Desktop\genesis is the directory, where all my files are placed.

*.php,*.css are the included file extensions.

*.dll, *.exe are the excluded file extensions.

I have searched genesis and replaced it with sudip.

Just copy the command and paste it in your Command Prompt. After executing the command, you will get a message similar to this:

That’s’ it! If you like it, you can download it from here.

Date: June 2, 2018 Tags: Files

This file came from another computer and might be blocked to help protect this computer

How to open and a view a JSON file on the web and in Windows 10

How to convert OXPS File to PDF

[email protected]

Sudip is a student who loves to engage with the latest technology & gadgets. Apart from writing about all things technology, he is a Photoshop junkie and a football enthusiast.

How to do a simple file search in cmd

I want to quickly search for a file given its name or part of its name, from the windows command line (not power shell). This is similar to opening explorer and using the search box at the top.

Note: dir can search based on a string template but it will not search in the subdirectories.

Note2: findstr can be used to search for a token inside files and has a recursivity flag; it’s funny that a more complex find can be easily discovered .

5 Answers 5

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

searches for all txt file in the directory tree. Before using it just change the directory to root using

you can also export the list to a text file using

and search within using

EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where

will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with

just wait for the prompt to return and don’t copy anything until then.

EDIT 2: If you are searching recursively and the output is big you can always use more to enable paging, it will show — More — at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

Use findstr on Windows to find text in files and command outputs

If you want to find specific text in files, in a command line output or elsewhere, you may use the findstr command on Windows to do so.

Findstr is a built-in tool of the Windows operating system that you may run from the command line to find text in files or in command line outputs.

You can use the application to filter command line outputs, search individual files or entire directory structures for files with matching text.

Читайте также:  Стиль windows для линукс

Run findstr /? from the command line to display all parameters and options that «Find String» supports.

Third-party tools like Notepad++, GGRep, or Everything support finding text in files as well.

Using findstr

You can run findstr from the command line or batch files. Open a new command line prompt by tapping on the Windows-key, typing cmd.exe and selecting the result.

  • /? — display the help text
  • /S — searches the directory and all subdirectories
  • /I — search is not case sensitive
  • /R — use search strings as regular expressions
  • /B — matches patterns at the beginning of lines
  • /P — skip files with non-printable characters
  • /V — print only lines that contain a match
  • /N — print the line number

Here is a list of examples that you may find useful:

  • ipconfig | findstr «192.168» — The command runs ipconfig and returns any result that matches 192.168. Any other result is ignored.
  • netstat | findstr «123.123.123.13» — Runs the netstat command and returns any result that matches the string (in this case the IP address).
  • findstr /c:»windows 10″ windows.txt — Searches the document windows.txt for the string «windows 10»
  • findstr «windows 10» windows txt — Searches for «windows» or «10» in the file.
  • findstr «windows» c:\documents\*.* — Searches any file under c:\documents for the string «windows».
  • findstr /s /i Windows *.* — Searches every file in the current directory and all subdirectories for the word Windows ignoring letter case.
  • findstr /b /n /r /c:»^ *FOR» *.bas— Returns any line that begins with FOR that are preceded by zero or more spaces. Prints the line number as well.

Findstr is a powerful command that you may use to search for strings in files or to filter command line output. You may use it to scan entire directory structures or drives for files that match the selected string or part of it, and to find specified text in command line outputs quickly.

Advanced options include returning content that is found at the beginning or end of lines, using regular expressions, or using wildcards.

Closing words

Findstr’s main advantage is that it is a built-in tool that you can run on any Windows machine. It is useful to find text in files quickly but works as a tool to filter the output of command line tools as well.

Now you: which program do you use to find text in files?

Use Notepad++ to find text in all files of a folder

Notepad++ is quite the versatile text editor for Windows even if you ignore the program’s plugin system for a moment which extends it even further.

One of the features that I make use of regularly is the program’s ability to search for text in all files of a folder that I specify.

Today for instance I was informed that the cookie handling for users who leave comments here on this site changed.

All I knew was that the cookie expiration time was set to the same day and not the next year. I suspected one of the plugins installed on the site responsible for that, but did not know which.

While I could analyze the issue using trial and error, by disabling plugins one by one and verifying if that operation resolved the issue, I decided to use NotePad++ for that instead.

The idea was to search through all plugin files and return any lines of code that would either alter cookies, or search for specific variables.

Find text in all files of a folder

Start Notepad++ on your system to get started with the operation. You don’t need to open a text file in the program on start, as it does not matter for the find operation that you are about to run.

Select Search > Find in Files from the menu. If you like keyboard shortcuts better, use Ctrl-Shift-F to open the search window instead.

The find in files configuration window is pretty easy to use as you can ignore most options if you don’t require them.

What you need to configure are the following fields:

  1. Find What: this is the search string that you want Notepad++ to find in the files.
  2. Directory: this is the root folder that contains all the files that you want searched. Notepad++ searches all subfolders as well by default.

All other fields are optional. If you leave everything as is, Notepad++ will crawl all files of the selected root folder and all subfolders that it contains, and return all hits at the end of the search.

Optional parameters may be useful however. You can change filters, so that only certain file types, e.g. *.css or *.php, or file names, finance.* are included in the search.

Читайте также:  Ubuntu mac os apps

You may also enable match whole word or match case options, or switch from a normal search mode to an extended search mode or one that uses regular expressions.

Last but not least, you may use the replace option to replace the text you entered with other text.

Click find all to get started. The search time depends largely on your selection, but should not take long.

Notepad++ returns all hits sorted by file and line afterwards.

All that is left is to go through the results line by line to find what you are looking for (which I did not by the way, but that is another story).

Notepad++

About Martin Brinkmann

Use the Windows Task Manager to find power leeching processes quickly

How to download YouTube videos with Internet Download Manager

How to turn off the News and Interests feature of Windows 10

How to turn off Text Predictions in Word and Outlook

Create your own SDelete shortcut for secure file deletion

How to sum numbers in LibreOffice Calc automatically

Comments

3rd rank in the best editors list, after Vim and Emacs.
Just forget hogs as Sublime or Atom.

I think Programmers’ Notepad 2 is much better than Notepad++, not least for its stability and Python script support.

As for the task at hand, I’d use Agent Ransack. It’s old but well maintained and very good at what it does.

Programmer’s Notepad 2 and Notepad++ are great, however PN2 has not been updated since 2011.
For lightweight activities, like checking small logs or readme files, I prefer SciTE. Notepad++ being based on Scintilla, allows me to use the same shortcuts as with SciTE.

An update to Agent Ransack was released (or at least brought to my attention by SUMo) yesterday!

Thanks for the tip, Martin!

Would SciTE be the best equivalent for Linux or is there something else? I’m trying to leave the Windows vale of tears. 😉

Out of context, but is there a program that lets you “send to” a file regardless of what format it is? If it’s a text file, it would show text, if it’s a picture, it would show you the picture, and if it’s a binary, it would show you the hex code?

Thanks for the info, Martin. Was wondering if it’s possible to exclude folders from the search. After a quick look it seems it isn’t possible, but a workaround would be to mark the folder you want excluded as Hidden (right-click/Properties). Notepad++ won’t look there by default (“In hidden folders” option, visible in the posted screenshot).

On a side note: I had to search two logs files the other with a combined size of 6GB .. LogExpert (not just for log files): haven’t tried any others

Nice article!
Wasn’t aware of that option, and to be honest haven’t used the in a very long time!
What I’ve been using for text search instead is my file search program, called ‘locate32’,i think it works 😉
But imma check it out!
Thanks

Yeah, I didn’t know about it either. I’m not a coder, so I don’t have much call for advanced functions in programs like Notepad++ and, accordingly, don’t go looking for them. I may check this one out, however.

I like pulling up XML files (which I do sometimes edit, e.g., for FreeFileSync) in Notepad++ because it does a nice job of coloring the tags and different nesting levels, resulting in fewer mistakes for an incipient Mr. Magoo like me. Also, by default it restores the previous “session” of open tabs. I install multiple versions of LibreOffice as “parallel” (

portable) installs but I have to manually edit each version’s bootstrap.ini file to point it to my LibreOffice user profile. Whenever a new version of LibreOffice comes out, it’s really handy to open its bootstrap.ini file in Notepad++ and have a tab containing a previously revised bootstrap.ini file already loaded and ready to copy from. It saves me the severe mental anguish of having to hunt down a “known-good” bootstrap.ini file each time.

Anyway, I like Notepad++ well enough, and Don Ho seems to be a pretty nice guy, even though I was disappointed to learn that he doesn’t actually lead a double life, coding in Paris during the day and entertaining tourists in Hawaii at night. (“Tiny bubbles…”)

I love NotePad++ and have been using it for years. However for my purposes, I prefer to find specific content, in text files for example, by invoking UltraSearch. I’m not claiming it’s best; perhaps it’s just what I’m used to.

Excellent tip Martin.

One feature that some people may not realize is there.

PSPad is another free editor. It has support for a wide range of file types.
It searches in directories, and sub-directories too. Its also free.

TextPad is very good and offers a similar feature list to PSPad. Its not free though.

Оцените статью