saperated comma and no new line after regular expression

Hi developer,

i am trying to read in text file. The file name is test.txt:

aa aa aa 4
bb bb bb 3
cc cc cc 5
dd dd dd 1
ee ee ee 2

Here is my sample windows powershell script:

$reg = ".........." 
Get-Content .\Test.txt|Select-String -Pattern  $reg -AllMatches | ForEach-Object { $_.Matches } | 
ForEach-Object { $_.Groups[0].value}

output:
aa
aa
aa
4
bb
bb
bb
3
cc
cc
cc
5
dd
dd
dd
1
ee
ee
ee
2

I want to display output like this:
aa,aa,aa,4
bb,bb,bb,3
cc,cc,cc,5
dd,dd,dd,1
ee,ee,ee,2

How to saperated comma and no new line after regular expression?

Thanks


May 18th, 2015 2:59am

What's in your regular expression? Is there any reason why you can't just do this?

Get-Content .\test.txt | % {$_ -replace " ",","}

Free Windows Admin Tool Kit Click here and download it now
May 18th, 2015 3:28am

My output look like when i run:
aa
aa
aa
4
bb
bb
bb
3
cc
cc
cc
5
dd
dd
dd
1
ee
ee
ee
2

This is not good idea. I am using regular expression

Please read my first comment
Thanks

May 18th, 2015 5:52am

if your input is as you post on top, the the following should work (just as the option by Braham20 should work)

$text = get-content .\test.txt 
$new_text = $text -replace (" ",",")
So either your regular expressions is not  
$reg = ".........." 

or test.txt is something else then given here.

(I'm not too at home with regular expressions, so do educate me if I'm wrong)

Free Windows Admin Tool Kit Click here and download it now
May 18th, 2015 9:05am

here you go:

$reg = "[a-zA-Z]+|\d+"

Get-Content .\test.txt|Select-String -Pattern  $reg -AllMatches | ForEach-Object { $_.Matches } |
ForEach-Object { $_.Groups[0].value}

Thanks

May 19th, 2015 12:39am

But why do you need the regex if you input file is already in a state where you can get the output you want with a small amount of code?

This is rough but you can keep the regex and it will get you the output you want. Not sure why it is necessary though.

$reg = "[a-zA-Z]+|\d+"
$narr = @()
$arr = Get-Content .\test.txt|Select-String -Pattern  $reg -AllMatches | ForEach-Object { $_.Matches } | 
ForEach-Object { $_.Groups[0].value} | group-object | % {$_.group -join ","} 
$even = 0..$arr.count | % {if($_ % 2 -eq 0){$_}}
$odd = 0..$arr.count | % {if(!($_ % 2 -eq 0)){$_}}

for($x = 0 ;$x-lt $even.Count -1 ;$x++){

$narr += $arr[$even[$x]..$odd[$x]] -join ","


}

Free Windows Admin Tool Kit Click here and download it now
May 19th, 2015 3:36am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics