1

I need to delete the first two columns in a CSV. I do not know the header names, they are not static. I figured out how to remove the first two rows, but not the first two columns. The sample code I am working with is below

$csv     = Import-Csv 'input.csv'
$headers = $csv[0].PSObject.Properties | select -Expand Name
$step    = 4

for ($i = 0; $i -lt $headers.Count; $i += $step) {
  $csv | select $headers[$i..($i+$step-1)] |
    Export-Csv "output_$($i/$step).csv" -NoType
}
3
  • I was about to refer you to your own question. stackoverflow.com/questions/27320245/…. The answer is almost there. Commented Dec 5, 2014 at 19:59
  • In your code you are already deciding which columns end up in the CSV file. All you have to do is manage that $headers[$i..($i+$step-1)] Commented Dec 5, 2014 at 20:02
  • If you just want to remove the first 2 columns and then split the rest in groups of 4, pick one of the answers here. If you want the columns removed from the first CSV (leaving just 2 columns in that CSV) see my response to your comment here. Commented Dec 5, 2014 at 22:17

3 Answers 3

4

If you wanted to skip the first X columns you just need to adjust your $headers statement

$headers = $csv[0].PSObject.Properties | select -Skip 2 -Expand Name

The above would skip the first 2 columns by not processing the first 2 headers. The rest of the code will group columns of 4 after those 2.

Sign up to request clarification or add additional context in comments.

Comments

2

This seems to work:

$csv     = Import-Csv 'input.csv'
$include = $csv[0].psobject.properties | select -ExpandProperty Name -Skip 2
$csv | select $include -skip 2 | export-csv output.csv -NoTypeInformation

That should take care of pruning off the first 2 columns and then skipping the first 2 rows.

Comments

2

I think just changing the 0 in the for loop to a 2 should do it:

$csv     = Import-Csv 'input.csv'
$headers = $csv[0].PSObject.Properties | select -Expand Name
$step    = 4

for ($i = 2; $i -lt $headers.Count; $i += $step) {
  $csv | select $headers[$i..($i+$step-1)] |
    Export-Csv "new_output_$($i/$step).csv" -NoType
}

1 Comment

@AnsgarWiechers, thanks for the edit! I had apparently lost my mind when I tried to format the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.