Home > Mobile >  Remove thousands separator from a line starting with Total Value
Remove thousands separator from a line starting with Total Value

Time:06-29

I have a text file which was generated with Powershell. There is a line that starts with Total Value: $ That line has a dollar amount which contains a thousands separator comma. I would like to delete that comma, but only in that line. I have tried using the following however it removes commas where I was not wanting this to occur.

$Files = Get-ChildItem "C:\Users\User\Summary.txt"
foreach ($file in $Files)
    {
        $file |
        Get-Content | 
        % {$_ -replace '([\d]),([\d])','$1$2' } | 
        out-file "C:\Users\User\Summary2.csv" -append -encoding ascii
    }

This works however again it is removing comma in areas of the file which I was hoping they could remain. Any assistance is appreciated.

CodePudding user response:

You can use

foreach ($file in $Files)
{
    (Get-Content $file -Raw) -replace '(?m)(?<=^Total\s Value:\s*\$[\d,]*),','' |
    out-file "C:\Users\User\Summary2.csv" -append -encoding ascii
}

See the regex demo.

Details:

  • Get-Content $file -Raw gets the contents of the file into a single string variable
  • (?m)(?<=^Total\s Value:\s*\$[\d,]*), is a regex that matches
    • (?m)
    • (?<=^Total\s Value:\s*\$[\d,]*) - a positive lookbehind that matches a location that is immediately preceded with
      • ^ - start of a line
      • Total\s Value: - Total Value: string with any one or more whitespaces between the two words
      • \$[\d,]* - a $ char and then zero or more digits or commas (a dollar price integer part)
    • , - a comma (that will be removed since the -replace operator is used with an empty replacement pattern (that can even be removed))
  • Related