Lawrence Knowlton
Lawrence Knowlton

Reputation: 99

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!

Upvotes: 5

Views: 16932

Answers (2)

Joey
Joey

Reputation: 354586

  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)
    

Upvotes: 7

CB.
CB.

Reputation: 60918

try

gc .\0.txt  | 
 % { $_ -replace '  +',"`t" } |   
     set-content .\temp.txt

Upvotes: 3

Related Questions