I am trying to write a script to combine multiple txt files in a folder to an output file, but I need to remove the header row. I've tried the following:
$outFile = new-item -path 'combined\combined.txt' -itemtype file -force
$inFiles = @(Get-ChildItem -Filter *.txt)
Get-Content $inFiles[0] -First 1 | Set-Content -Encoding Utf8 $outFile
Get-ChildItem -Recurse -Include "*.txt" | get-content | Select -Skip 1 |
Out-File -Append -encoding ASCII $outFile
I've also tried looping but would run into errors about the file being in use or the powershell script just stopping and not combining all files
foreach ($file in $inFiles) {
$from = Get-Content -path $file |
Select-Object -Skip 1
Add-Content $outFile -value $from }
Any help would be greatly appreciated!
CodePudding user response:
I think you're overcomplicating this ... this should be enough:
Get-ChildItem -Filter *.txt |
Select-Object -First 1 |
ForEach-Object {
Get-Content -Path $_.FullName |
Select-Object -First 1
} |
Out-File -FilePath 'combined\combined.txt'
Get-ChildItem -Filter *.txt |
ForEach-Object {
Get-Content -Path $_.FullName |
Select-Object -Skip 1
} |
Out-File -FilePath 'combined\combined.txt' -Append
The first snippet creates the output file with only the headers taken from the first input file. The second snippet gets the all lines except of the first one from all input files.
Are you sure it is about txt files? If it'd be about CSV files with the same headers it would be easier. ;-)