none
Text file processing using Powershell RRS feed

  • Question

  • I have a text file with n number of records and each records contains two columns with delimited by tab. I am reading this text file and performing some mapping on the second column using the Powershell scripting. I am able to perform read the text file and able to perform mapping. But when i write the results using set-content command, i am getting below result.

    Input File:

    4803 6000000

    4802 6000000

    4803 6000000

    4803 5000000

    Output File:

    @{Column1=4803; Column2=5000000;}

    @{Column1=4802; Column2=6000000;}

    @{Column1=4803; Column2=5000000;}

    @{Column1=4803; Column2=5000000;}

    I am not sure why i am getting Column name in each record. I don't want to see the result like this @{Column1=4803; Column2=5000000;} . But it should be like this - 4803 5000000. Please could you help me to remove the special character and column names in the output file.

    Expected Result:

    4803 5000000

    4802 6000000

    4803 5000000

    4803 5000000

    Script:

    $fields = Get-Content Temp.txt
    $results = @()
    foreach($i in $fields)
    {
        $field  = $i -split '\t' -replace '^\s*|\s*$'
        $field1 = $field[0]
        $field2 = $field[1]
        if ($field1 -eq "4803" -and $field[2].substring(0,2) -eq "60")
            {
                $field2 = "5000000"
            }
        else
            {
                $field2 = $field[1]
            }
                $details = @{       
                        Column1     = $field1
                        Column2     = $field2
                    }
            $results += New-Object PSObject -Property $details 
        }
       $results | Select-Object Column1, Column2 | Set-Content -path Temp.txt    [Environment]::Exit(0)

    Friday, November 4, 2016 4:55 PM

Answers

  • (gc .\tmp.txt) | %{

            $_.trim() -replace '\t{1,}',' ' -replace '^4803 6','4803 5'

    } | sc .\tmp.txt


    Friday, November 4, 2016 5:51 PM

All replies

  • $file = Import-Csv temp.txt -header Field1, Field2 -Delimiter "`t"
    # do processing on fields
    $outfile = $file | ConvertTo-Csv -Delimiter "`t" -NoType
    $outfile[1..($file.Count) | Out-File temp.txt
    
    
    


    \_(ツ)_/


    Friday, November 4, 2016 5:59 PM
    Moderator
  • I fixed the typo. Yes I convert to a CSV to remove the header before outputting the original tab delimited format.

    The OP can add his update code back in without the need to split and parse everything.  Just do the field parts.


    \_(ツ)_/


    Friday, November 4, 2016 6:38 PM
    Moderator
  • Thanks for your help. But I don't want use "Import-CSV".
    Monday, November 7, 2016 5:00 PM