Reputation: 2205
I'm trying to find out how to use powershell to find and delete lines without certain string pattern in a set of files. For example, I have the following text file:
111111
22x222
333333
44x444
This needs to be turned into:
22x222
44x444
given that the string pattern of 'x' is not in any of the other lines.
How can I issue such a command in powershell to process a bunch of text files?
thanks.
Upvotes: 2
Views: 2323
Reputation: 126762
This will process all txt files from the working directory. Each file content is checked and only lines that have 'x' in them are allowed to pass on. The result is written back to the file.
Get-ChildItem *.txt | ForEach-Object{
$content = Get-Content $_.FullName | Where-Object {$_ -match 'x'}
$content | Out-File $_.FullName
}
Upvotes: 2
Reputation: 3269
dir | foreach { $out = cat $_ | select-string x; $out | set-content $_ }
The dir
command lists the files in the current directory; the foreach
goes through each file; cat
reads the file and pipes into select-string
; select-string
finds the lines that contains the specific pattern, which in this case is "x"; the result of select-string
is stored in $out
; and finally, $out
is written to the same file with set-content
.
We need the temporary variable $out
because you cannot read and write the same file at the same time.
Upvotes: 3