My Technical Notes

Friday, 24 April 2015

Import-OrgTable PowerShell Function

Given a file containing an `org-mode` table. e.g: `politicians.org`:


| Forename | Surname  | Party         |
|----------+----------+---------------|
| Nick     | Clegg    | Lib Dems      |
| Ed       | Miliband | Labour        |
| David    | Cameron  | Conservatives |

We can import it using:


Import-OrgTable "...\path\to\politicians.org"

Here is the definition:


Function ConverOrgTableToCsv([string]$orgTablePath, [string]$outCsvPath) {
    $csv_content = Get-Content $path_ | % {
        $line = $_.ToString().Trim();
        if (-not ($line.StartsWith("|-") -and $line.EndsWith(("-|")))) {
            $s1 = [Regex]::Replace($line, "^\s*\|\s*", "")
            $s2 = [Regex]::Replace($s1, "\s*\|\s*$", "")
            $elems = [regex]::Split($s2, "\s*\|\s*") | % { if ($_.Contains(",")) { "`"$_`"" } else { $_ } }
            [string]::Join(",", $elems);
        }
    }

    $csv_content | Out-File -FilePath $outCsvPath
}

# http://stackoverflow.com/questions/885349/how-to-write-a-powershell-script-that-accepts-pipeline-input
# add something to do with accepting a file fro
Function Import-OrgTable {
    param(  
    [Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [Alias('FullName')]
    [String[]]$FilePath
    ) 

    process {
       foreach ($path in $FilePath)
       {
            $path_ = Resolve-Path $path
            $tempPath = Join-Path (Split-Path $path_) ([Guid]::NewGuid().ToString() + ".csv")

            ConverOrgTableToCsv $path_ $tempPath

            Import-Csv $tempPath

            Remove-Item $tempPath
       }
    }
}

No comments: