# Convert-Delimiter.ps1 # A function to convert between different delimiters. E.g.: commas to tabs, etc. ################################################################## # Written primarily as a way of enabling the use of Import-CSV when # the source file was a columnar text file with data like services.txt: # ip service port # 13.13.13.1 http 8000 # 13.13.13.2 https 8001 # 13.13.13.1 irc 6665-6669 # # Sample Use: # Get-Content services.txt | Convert-Delimiter " +" "," | Set-Content services.csv # would convert the file above into something that could passed to: # Import-Csv services.csv # # Get-Content Delimited.csv | Convert-Delimiter "," "`t" | Set-Content Delimited.tab # would convert a simple comma-separated-values file to a tab-delimited file # Function Convert-Delimiter([regex]$from,[string]$to) { process { $_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:((?:.(?!$from))*.)(?:$from|`$))","Þ`$1`$2Þ$to" $_ = $_ -replace "Þ(?:$to|Þ)?`$","Þ" $_ = $_ -replace "`"`"","`"" -replace "`"","`"`"" $_ = $_ -replace "Þ((?:[^Þ`"](?!$to))+)Þ($to|`$)","`$1`$2" $_ = $_ -replace "Þ","`"" -replace "Þ","`"" $_ } } # Import-Delimited # A replacement for Import-Csv that can handle other delimiters, and can import text from the pipeline # # Sample Use: # Import-Delimited " +" services1.txt # OR # ls services*.txt | Import-Delimited " +" # OR # gc services2.txt | Import-Delimited " +" Function Import-Delimited([regex]$delimiter=",", [string]$PsPath="") { begin{ $script:tmp = [IO.Path]::GetTempFileName() write-debug "Using tempfile $($script:tmp)" Function Import-String([string]$inputString){ if($inputString.Length -gt 0 ) { write-debug "Importing $inputString" if(($inputString -as [IO.FileInfo]).Exists) { Get-Content $inputString | Convert-Delimiters $delimiter "," | Add-Content $script:tmp } elseif( ((Join-Path $pwd $inputString) -as [IO.FileInfo]).Exists) { Get-Content (Join-Path $pwd $inputString) | Convert-Delimiters $delimiter "," | Add-Content $script:tmp } else { $inputString | Convert-Delimiters $delimiter "," | Add-Content $script:tmp } } else { write-debug "Nothing to Import" } } Import-String $PsPath } process{ Import-String $_ } end { Import-Csv $script:tmp } }