문제

I have 3 .csv files that I am combining into one. This bit of code works:

    Get-ChildItem 'C:\Scripts\testing\csvStuffer\temp\Individual.*.csv' | 
        ForEach-Object {Import-Csv $_} | 
        Export-Csv -NoTypeInformation 'C:\Scripts\testing\csvStuffer\temp\MergedCsvFiles.csv'

The problem is that each .csv file has a header and a footer. I do not want to keep the header or footer from any of the files. Any suggestions of what I need to add to the above code to remove the headers and footers??? Thanks!

도움이 되었습니까?

해결책

This is not the most elegant solution but it worked for my test files.

Get-ChildItem 'C:\Scripts\testing\csvStuffer\temp\Individual.*.csv' | 
        ForEach-Object {
            $filecontent = get-content $_ | select-object -skip 1;
            $filecontent | select -First $($filecontent.length -1) | Set-Content -Path $_;
        };

Skipping the first line is easy with select-object. Dropping the last line requires a bit more work, but since get-content returns an array of lines, you can just grab all but the last element in that array.

다른 팁

Looks like alroc already gave an answer, but since I already had it written up I figured I'd post this too. It doesn't load it all into a variable, it just reads each file, strips the first and last line of the current file, and then pipes to out-file with -append on it.

gci 'C:\Scripts\testing\csvStuffer\temp\Individual.*.csv' | %{
$(gc $_.fullname|skip 1)|select -First ($(gc $_.fullname|skip 1).count-1)
}|Out-File -Append 'C:\Scripts\testing\csvStuffer\temp\MergedCsvFiles.csv'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top