Reputation: 700
I would like to get content from files in a folder (ignoring the header lines, since some file may ONLY contain the header). But in the output, I would like to include the filename from which the line is read. So far, I have the following:
Get-ChildItem | Get-Content | Where { $_ -notlike "HEADER_LINE_TEXT" } | Out-File -FilePath output_text.txt
I've tried to work with creating a variable in the Where block, $filename=$_.BaseName
, and using it in the output, but this didn't work.
EDIT:
I ended up with the following:
Get-ChildItem -Path . |
Where-Object { $_.FullName -like "*records.txt"; $fname=$_FullName; } |
Get-Content |
Select-Object { ($fname + "|" + $_.Trim()) } |
Where { $_ -notlike "*HEADER_LINE_TEXT*" } |
Format-Table -HideTableHeaders |
Out-File -FilePath output_text.txt
This looks lengthy, and can probably be made shorter and clearer. Can someone help with cleaning this up a bit? I'll either post the solution, or vote for a cleaner solution, if one is posted. Thanks.
Upvotes: 0
Views: 2684
Reputation: 10054
This looks like a case where it would make it more readable to not make it a one liner at cost of a little additional memory usage.
$InputFolder = "C:\example"
$OutputFile = "C:\example\output_text.txt"
$Files = Get-ChildItem $InputFolder | Where-Object { $_.FullName -like "*records.txt"}
Foreach ($File in $Files) {
$FilteredContent = Get-Content $File.FullName | Where-Object {$_ -notlike "*HEADER_LINE_TEXT*"}
$Output = $FilteredContent | Foreach-Object { "$($File.FullName)|$($_.Trim())" }
$Output | Out-File $OutputFile -Append
}
If you are going to go oneliner style for brevity, you could cut down on length by using position for parameters and using aliases.
Here are a couple other changes:
where
block.$_
and fullname
. Format-Table
isn't needed because you already have the string you want to outputwhere
earlier so that you don't trim()
on lines you are just going to filterforeach
instead of select
+
operator for string concatenation, instead using $()
to evaluate inside parenthesis gci . |
? { $_.FullName -like "*records.txt"; $fname=$_.FullName } |
% { gc $_.FullName } |
? { $_ -notlike "*HEADER_LINE_TEXT*" } |
% { "$fname|$($_.Trim())" } |
Out-File output_text.txt
Upvotes: 1