Power shell: Merge rows in the file based on a pattern

Posted: November 4, 2015 in PowerShell
Merge_lines_Using_Stream

$fso = new-object -com scripting.filesystemobject
$folder = $fso.getfolder(“H:\Desktop\WALMART\”)

$Driectory_FINAL = “H:\Desktop\WALMART_BKP”

foreach ($f in $folder.files) {
$temp = gci $f.path | % {$_.BaseName}
$File_NAME = $temp +“_BKP.TXT”

#this will give the final path with file name dynamically
$FULL_PATH_WITH_FILE_NAME = $Driectory_FINAL+”\”+ $File_NAME

#$content = Get-Content $f.path | select -Skip 2
$file = New-Object System.IO.StreamReader -Arg $f.path
$stream = [System.IO.StreamWriter] $FULL_PATH_WITH_FILE_NAME
while ($line = $file.ReadLine())
{
$first_column = $line.split(‘,’)[0]

# skip last 2 lines
if(($line.split(‘,’)[0] -eq ’98’) -Or (’99’ -eq $line.split(‘,’)[0]) )
{
Write-host “Do nothing “
}
# check for the line not equal to 03 and equal to 49

if ($line.split(‘,’)[0] -eq ’03’){
$new_data = $line
}

# Second loop
else {
$new_data = $new_data + $line
if ($line.split(‘,’)[0] -eq ’49’){
Write-Host $new_data
$stream.WriteLine($new_data)
}
}
}
$stream.close()
$file.close()
# end of the second foreach loop
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s