takeitback
takeitback

Reputation: 112

Join text files in Powershell

I've been trying to format the output of a repadmin /showobjmetadata script into a table for a while now in Powershell and the further I get, the more convoluted the script tends to be. Long story short, I'm at a point where I have 2 files I need to combine.

User.txt:

john doe
jane smith
generic name

data.txt:

Absent, <date>
Absent, <date>
Absent, <date>

I want to combine these files so they look like this:

Absent,<date>,John Doe
Absent,<date>,Jane Smith
Absent,<date>,generic name

in one single text document.

I've tried several -join, foreach, New-object, and Select-String approaches, but I'm getting nowhere. Any help would be much appreciated.

Upvotes: 0

Views: 74

Answers (1)

sodawillow
sodawillow

Reputation: 13176

Many solutions, here's one (I assumed you deliberately removed the spaces before <date>):

$user = Get-Content "user.txt"
$data = Get-Content "data.txt"

$combined = for($count = 0; $count -lt $data.Count; $count++) {
    $dataWithoutSpaces = $data[$count] -replace " "
    "{0},{1}" -f $dataWithoutSpaces, $user[$count]
}

$combined | Out-File "result.txt"

result.txt:

Absent,<date>,john doe
Absent,<date>,jane smith
Absent,<date>,generic name

There must be some one-liners, I guess : ).

Upvotes: 2

Related Questions