1

Hi how do i replicate this BASH script into powershell? It is taking a basic string and grabbing these certain chunks and putting a pipe inbetween and writing it out to the csv file. I know how to do the get-content and the output to the csv but what is the best way to chop up a string in powershell?

`cat /app/$filename |cut  -c1-9,19-138,139-198,199-238,239-240,241-245,287-296 --output-delimiter="|" >> /app/CSVs/$filename.csv`

I've used split() before but it doesn't seem like the correct way to do it. I'm thinking along the lines of looping through each line and saving each piece of that line and saving to a new string var and adding the delimiter for each section. This seems awfully inefficient.

Thoughts?

The source file is structured by character position with lots of spaces. each field has a set amount of character spaces. (It's basically a database file but in really simple txt format)

1-9 = ID (9 chars long)
19-138 = business_name (120 chars long)
139-198 = address (60 chars long)
198-237 = city (40 chars long)
238-239 = state (2 chars long)
240-244 = zip_code (5 chars long)
286-295 = phone (10 chars long)

I think using $string.substring(char#,length) will work with looping but the more help the better.

The output should look like

123456789|acme business <lots of spaces>|1234 main st <lots of spaces>|etc...
wanney
  • 43
  • 1
  • 7
  • Could you provide source file and resulting CSV example? Is source file structured (has some kind of delimiters?) or you just grabbing chunks from predetermined positions? – beatcracker May 22 '15 at 14:46
  • added info to the post. And yes to your last question. I am just grabbing chunks from predetermined positions. – wanney May 22 '15 at 15:10

2 Answers2

0

Looks like a job for the new PS 5 cmdlet ConvertFrom-String:

Unfortunately, I haven't tried it yet, so I can't provide an example. But it also can be done using regex:

Get-Content -Path '.\db.txt' |
    ForEach-Object{$_ -replace '^(.{9})(.{120})(.{60})(.{40})(.{2})(.{5})(.{10})$', '$1|$2|$3|$4|$5|$6|$7'} |
        Set-Content -Path '.\db.csv'

Get-Content \ Set-Content are quite slow, so to speed up processing you could switch to StreamReader\StreamWriter. See my answer for this question: More-efficient way to modify a CSV file's content, where I use them in the script to speed up things.

Community
  • 1
  • 1
beatcracker
  • 6,714
  • 1
  • 18
  • 41
0
$subChar =0,18,138,198,238,240,286 
$subLength =9,120,60,40,2,5,10 

$file = Get-content 'C:\Users\jwannemacher\Desktop\out.txt'
Foreach($line in $file)
{
    $lineCounter
    $array = @()
    $lineLoop = 0
    $charLoop = 0

    foreach($sub in $subChar)
    {
        $word = $line.Substring($subChar[$charLoop],$subLength[$charLoop])
        $array += $word
        $charLoop++
    }
$array -join '|' | Out-File C:\file1.csv -Append
wanney
  • 43
  • 1
  • 7