Share via


Merge two lines into one from a text file

Question

Tuesday, March 18, 2014 4:25 AM

Hi

I am getting the data in the below format in a text file

servername1 192.168.0.2:80
enabled
servername2 192.168.5.23:443
enabled
servername3 192.168.25.16:80
disabled
serveranme4 192.168.0.52:443
disabled

I want to merge the two lines and get the output like

servername1 192.168.0.2:80 enabled
servername2 192.168.5.23:443 enabled
servername3 192.168.25.16:80 disabled
serveranme4 192.168.0.52:443 disabled

Thanks

All replies (5)

Tuesday, March 18, 2014 6:59 AM ✅Answered | 1 vote

first google query "merge lines powershell"

http://social.technet.microsoft.com/Forums/windowsserver/en-US/b998600b-a7aa-4586-9c8f-bebadf1f82f7/merge-lines-in-text-file-into-one-row-in-powershell?forum=winserverpowershell

.. worked


Tuesday, March 18, 2014 3:58 PM ✅Answered

Not quite correct by my testing.  Try:

$i=0
Get-Content .\test.txt | ForEach {
    If ($i%2){
        ("$Keep $($_)").Trim()
    }Else{
        $keep=$_
    }$i++
}

Tuesday, March 18, 2014 2:23 PM

Assuming the file is named notmerged.txt 

$l=''; gc notmerged.txt | % {if ($l -ne ''){$l+' '+$_;$l=''}else{$l=$_}}

Tuesday, March 18, 2014 3:37 PM

Yet another way...

$i=0
Get-Content .\test.txt | ForEach {
    If ($i%2){
        $keep=$_
    }Else{
        ("$($_) $Keep").Trim()
    }$i++
}

Boe Prox
Blog | Twitter
PoshWSUS | PoshPAIG | PoshChat | PoshEventUI
PowerShell Deep Dives Book


Tuesday, March 18, 2014 4:23 PM

Not quite correct by my testing.  Try:

$i=0
Get-Content .\test.txt | ForEach {
    If ($i%2){
        ("$Keep $($_)").Trim()
    }Else{
        $keep=$_
    }$i++
}

Good catch!

Boe Prox
Blog | Twitter
PoshWSUS | PoshPAIG | PoshChat | PoshEventUI
PowerShell Deep Dives Book