Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Regex: Replace only multiple spaces with tabs

This is a Powershell question similar to what was being asked in this C# question: C# Question Link

I have fixed width column data in a text file that are of variable length, so I'd like to delimit the data with tabs. To do so, I want to use Powershell to read in the file, replace only multiple spaces with tabs using a Regex expression, keep the end of lines intact and output it to a temp file. I'll then rename it to the original.

I've searched the web and only seem to be able to find bits and pieces. Any assistance with this would be greatly appreciated!

like image 833
Lawrence Knowlton Avatar asked Jan 14 '23 04:01

Lawrence Knowlton


2 Answers

  1. Fetch the contents

    $content = [IO.File]::ReadAllText('foo.txt')
    
  2. Replace at least two spaces by a single tab:

    $content = $content -replace ' {2,}', "`t"
    
  3. Write back to a file

    [IO.File]::WriteAllText('footab.txt', $contents)
    
like image 158
Joey Avatar answered Jan 30 '23 22:01

Joey


try

gc .\0.txt  | 
 % { $_ -replace '  +',"`t" } |   
     set-content .\temp.txt
like image 42
CB. Avatar answered Jan 30 '23 22:01

CB.