brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Select-String -List names the files that contain a word

Files
~/tips/tip-windows-select-string-list-files

Select-String -Pattern 'example.com' -List |

Lists only the files in a folder tree whose text contains a pattern.

Sometimes I do not need to see every line. I just want to know which of the files in a folder mention a setting or a hostname.

The -List switch of Select-String returns only the first matching instance from each input file. The docs call this the most efficient way to retrieve a list of files whose contents match the regular expression, because it stops reading a file at its first match.

Get-ChildItem -Path C:\Configs -Filter *.conf -Recurse |
    Select-String -Pattern 'example.com' -List |
    Select-Object -ExpandProperty Filename

Here Get-ChildItem walks the folder and its subfolders, and each file object goes to Select-String. The docs state that file objects piped in are treated as paths, so the file contents are searched and not the object text. Finally, Select-Object -ExpandProperty Filename keeps just the file names, one per line, since the docs say the match objects have properties such as Filename and Line.

Another switch fits the same job. -Quiet returns a boolean, $true if the pattern is found and $null if not, which suits a quick check in a script:

Select-String -Path C:\Configs\*.conf -Pattern 'example.com' -Quiet

Use -Quiet when you only need yes or no, and -List when you need the names.

The caveat: the pattern is a regular expression by default, so the dot in example.com matches any character. For an exact string add -SimpleMatch. And the docs warn that badly designed regular expressions can cause denial of service problems, which is a good reason to keep patterns simple when the input is untrusted.

As the docs say, matching is case-insensitive by default; add -CaseSensitive if it matters.

Further reading: Select-String

More Files tips sha256sum -c --ignore-missing SHA256SUMS xxhsum -H64 backup.tar > backup.xxh unzip -j archive.zip -d out/ Files > More > Select > pick files > More > Compress ls -lhS /var/log All Files tips (15) All topics

Link