0

Sorry if this question has already been asked, but I can't for the life of me find a valid answer.

I have a bunch of .txt files each containing a column of content. I would like to merge them in one .csv where the columns will be next to each other.

So if the first input in1.txt is:

banana
pear
apple
orange

and the second one, in2.txt is

airplane
truck
car
bus

I would like the resulting csv, say out.csv, to be:

banana,airplane
pear,truck
apple,car
orange,bus

Is there a way to do that with Powershell?

4
  • 3
    Yes there is a way to do that. I would suggest looking at the Get-Content, New-Object, and Export-CSV commands and writing some code. When you have specific code issues you can post back here and we will help you. Commented Jun 12, 2018 at 13:17
  • Also be aware that the text files need to have exactly the same number of entries in each file or else you will need to write your code to handle situations where they do not. Commented Jun 12, 2018 at 13:23
  • @EBGreen thanks for your input. I was actually completely stuck trying to concatenate objects instead of making a loop, so much so that I didn't have anything that remotely worked. This is why I didn't publish any code, because it didn't need debugging but completely rethinking. Sorry if I came across as not wanting to give it a try, and thanks for your help! Commented Jun 12, 2018 at 14:05
  • No problem. In the future though posting what you have tried even if it is not close at all is a good idea. If nothing else it gives us some indication of where your knowledge level is so we can craft an answer that is more appropriate for you. Commented Jun 12, 2018 at 15:00

1 Answer 1

1

Well i'm agree with EBGreen both comments, but to guide you with some direction...

In case your both files are in the same length, you can use simple for loop, if not, you should work a bit harder, but you can start with this as an idea...

$txt1 = Get-Content C:\txt1.txt
$txt2 = Get-Content C:\txt2.txt

$csv = @()
for ($i = 0; $i -lt $Txt1.Count; $i++){
$row = "" | Select txt1,txt2
$row.txt1 = $txt1[$i]
$row.txt2 = $txt2[$i]
$csv += $row
}

$csv | Export-Csv c:\txt.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! That solved it. I was completely stuck with attempts at concatenating the different objects, so much so that I didn't think about making a loop, which in retrospect seems obvious. Thank you for your help!
Just as an FYI, if the files are very large at all using an ArrayList rather than an Array is much faster.
sure, but just to keep it simple

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.