Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: How to locate nth position of \"^\" in record, Cut 2 Cols & INS a EOR \"|\"

$
0
0

hi,

Not quite sure what your goal is, however I would look into building a function.

To list all files matching *TAT*.txt


get-childitem -Filter *TAT*.txt

To read the contents of a file:


get-content -path file.txt

If we assign the content to a variable:


$filecontent = get-content -path file.txt

Then we can create an array every line by splitting at each new line(zero based):


$Array = $filecontent -split [environment]::Newline

Say we have this line “1^2^3^4^5^6^7^8^9^10^11^12^13^14^15^16″ in a file, lets split it to an array and keep the 15 first items:


[string]$line = "1^2^3^4^5^6^7^8^9^10^11^12^13^14^15^16"
$linearray = $line.split("^")
$ReducedArray = $linearray[0..14]

So how do we go the other way, from array to a string, separating all fields with a “^” and adding an “|” to the end?


[string]$newline = ($ReducedArray -join "^") + "|"

Now instead of replacing each line, I would add each new line to a new array and save the array when I had processed all the lines in the file. To add an item to an array:


$ArrayOfNewContent = @()
$ArrayOfNewContent += $newline

Next is creating an string to hold all the items in the ArrayOfNewContent:


[string]$NewFileContent = ($ArrayOfNewContent -join "") + [environment]::NewLine
set-content -path c:\temp\file.txt -value $NewFileContent

You now have enough information to create this function:


function Set-FileNewContent
{
[cmdletbinding()]
Param(
        [string[]]$FilePath
)
    
    foreach($File in $FilePath)
    {
        $NewContentArray = @()
        Write-Verbose "Processing file $file"
        $FileContent = Get-Content -path (Resolve-Path -path $file)
        $Array = $FileContent -split [System.Environment]::Newline
        Foreach ($line in $Array)
        {           
            $LineArray = $line.split("^")
            $ReducedArray = $linearray[0..14]
            [string]$newline = ($ReducedArray -join "^") + "|"
            $NewContentArray += $newline + [System.Environment]::NewLine
        }
        [string]$NewFileContent = ($NewContentArray -join "") 
        Write-Verbose "Saving file $file"
        Set-Content -Path $File -value $NewFileContent
    }
}

You can call the function like so:


Set-FileNewContent -FilePath (Get-ChildItem -Filter "*tat*.txt") -Verbose

Note the -verbose switch is not needed, however it gives you feedback as the script progresses.

Cheers

Tore


Viewing all articles
Browse latest Browse all 13067

Trending Articles