TOPIC: FINDSTR
Searching file contents using PowerShell
25th October 2018Having made plenty of use of grep
on the Linux/UNIX command and findstr
on the legacy Windows command line, I wondered if PowerShell could be used to search the contents of files for a text string. Usefully, this turns out to be the case, but I found that the native functionality does not use what I have used before. The form of the command is given below:
Select-String -Path <filename search expression> -Pattern "<search expression>" > <output file>
While you can have the output appear on the screen, it always seems easier to send it to a file for subsequent use, and that is what I am doing above. The input to the -Path switch can be a filename or a wildcard expression, while that to the -Pattern can be a text string enclosed in quotes or a regular expression. Given that it works well once you know what to do, here is an example:
Select-String -Path *.sas -Pattern "proc report" > c:\temp\search.txt
The search.txt file then includes both the file information and the text that has been found for the sake of checking that you have what you want. What you do next is up to you.
Command line file comparison in Windows
20th August 2012While UNIX and Linux both have the diff command for comparing the contents of text files, the Windows counterpart was unknown to me until recently. Its name is fc
, and it looks as if the f is for file and c is for comparison, though I cannot confirm that as of now. The usage of that command is not dissimilar to the way that things work with diff. Here is an example command:
fc file1.txt file2.txt > file3.txt
This compares file1.txt with file2.txt and sends the output to file3.txt. Any differences between the two files being compared appear to be more clearly labelled than in the diff output's < and > labels. That verbosity could have its uses, but the existence of the fc
command is stopping envious glances at the diff one for now, just as findstr
is doing the same in comparison with grep
.