I want to find all files in a particular directory that contain a certain string. Specifically, I want to find the carriage return (\r) and then manually go through the files and remove occurrences of it. I don't want PowerShell to remove them because there may be certain subdirectories that require them in my directory structure.
2 Answers
Your question seems to boil down to: I want to find all files in a directory that contain the carriage return. Is there any reason why these answers are not adequate?
For example:
This should give the location of the files that contain your pattern:
Get-ChildItem -recurse | Select-String -pattern "dummy" | group path | select name

- 547
- 6
- 12
-
1I tried -pattern "\n" and -pattern "\r" but nothing was returned. For some reason -pattern "\t" returned files. – user8056359 Jul 30 '17 at 01:54
-
Must admit, I just tried this and it failed to find strings from an excel file.. shame – BugFinder Jun 25 '18 at 13:54
You could use Select-String
to find patterns in a group of files, however this will only search for the pattern within each line of text. It will not work in your case because you want to search for the line separator.
An easier way is to use Get-Content
, this converts a file to an array of strings, one item per line. Therefore any file that has a return and a line feed will produce an array with more than one item. Try something like this:
Get-ChildItem -recurse | ? {(Get-Content $_.FullName).count -gt 1}
If your files are quite large and you want to speed it up then add a -TotalCount
like this:
Get-ChildItem -recurse | ? {(Get-Content $_.FullName -TotalCount 2).count -gt 1}
This will only find where the return and line feed are together, if you want instances where they could appear on their own then you will need to force Get-Content
to not read the file as an array of strings but as one big string instead. Something like this:
Get-ChildItem -recurse | ? {[regex]::Matches((Get-Content $_FullName -Raw), '[\r\n]+').Count -gt 0}

- 5
- 2
- 5

- 10,768
- 3
- 42
- 56