Home > front end >  Combining csv files to but keeping separate columns in Powershell
Combining csv files to but keeping separate columns in Powershell

Time:10-04

I have two csv files (FileA.csv and FileB.csv), each with one column. I'm trying to combine them in to one csv file, but keeping two separate columns (then applying some conditional formatting afterwards). So far, I've only been able to append the two lists and end up with one column of all the data. Is there any way to have Column A with FileA.csv and then Column B with FileB.csv? Thanks!

CodePudding user response:

This script below will concatenate the content of both files and print the lines side by side.

It is considering the same number of lines in both files, if it isn't your case, you have to apply a logic to print blank spaces or whatever you want to at that line/position.

Code explanation:

  1. Get the content of each file and store it on a variable
  2. Count the lines of file-a.csv
  3. Print the number of lines (just to check it)
  4. Iterate over each line

code:

$a_file = Get-Content file-a.csv
$b_file = Get-Content file-b.csv

gc .\file-a.csv | %{$a_lines  }

echo $a_lines
5

for($i=0; $i -lt $a_lines; $i  ) {
    Add-Content -Path file-c.csv -Value ($a_file[$i]   ";"   $b_file[$i])
}

result:

file a line 1 file b line 1

file a line 2 file b line 2

file a line 3 file b line 3

file a line 4 file b line 4

file a line 5 file b line 5

  • Related