Powershell text procesing: Join specific lines of a txt file

Viewed 79

I have to process some text and got some difficulties:

The text .\text.txt is formatted like that:

name,
surname,
address,

name.
surname,
address,

etc.

What I want to achieve is join the objects that ends with the "," like this:

name,surname,address

name,surname,address

etc

I was working on something like this:

$content= path to the text.txt
$result= path to the result file

Get-Content -Encoding UTF8 $content | ForEach-object {
        if ( $_ -match "," ) {
           ....join the selected lines.... 
        }
    } |Set-Content -Encoding UTF8 $result

What I need to consider is also that lines which terminate with "," may have a next line empty which should be a CR in the $result

3 Answers

all your terms ends with a , so you could use regex:

$content= "C:\test.txt"
$result= "path to the result file"

$CR = "`r`n"

$lines = Get-Content -Encoding UTF8 $content -raw 
$option = [System.Text.RegularExpressions.RegexOptions]::Singleline 

$lines = [regex]::new(',(?:\r?\n){2,}', $option).Replace($lines, $CR + $CR)
$lines = [regex]::new(',\r?\n', $option).Replace($lines, ",")

$lines | Out-File -FilePath $result -Encoding utf8

result:

name,surname,address

name1,surname,address

name,surname,address

name,surname,address

You can do this by splitting the blocks of data on the empty newlines first:

# read the content of the file as one single multiline string
$content = Get-Content -Path 'Path\To\The\file.txt' -Raw -Encoding UTF8
# split on two or more newlines and dispose of empty blocks
$content -split '(\r?\n){2,}' | Where-Object { $_ -match '\S' } | ForEach-Object {
    # trim the text block, split on newline and remove the trailing commas (or dots)
    # output these joined with a comma
    ($_.Trim() -split '\r?\n' ).TrimEnd(",.") -join ','
} | Set-Content -Path 'Path\To\The\NEW_file.txt' -Encoding UTF8

Output:

name,surname,address
name,surname,address

Below piece of code will give the required result.

$content= "Your file path"
$resultPath = "result file path"

 Get-Content $content | foreach {
 
  $data  = $_
  if($data -eq "address,")
  {
    $NewData = $data -replace ',',''
    $data = $NewData + "`r`n" 
  }
  $out = $out + $data
  
 }

$out | Out-File $resultPath
Related