2

I need to add the quotation mark to a text file that contains 500 lines text. The format is inconsistent. It has dashes, dots, numbers, and letters. For example

1527c705-839a-4832-9118-54d4Bd6a0c89

16575getfireshot.com.FireShotCaptureWebpageScreens

3EA2211E.GestetnerDriverUtility

I have tried to code this

$Flist = Get-Content "$home\$user\appfiles\out.txt"
$Flist | %{$_ -replace '^(.*?)', '"'}

I got the result which only added to the beginning of a line.

"Microsoft.WinJS.2.0

The expected result should be

"Microsoft.WinJS.2.0"

How to add quotation-mark to the end of each line as well?

mklement0
  • 382,024
  • 64
  • 607
  • 775
JamesNEW
  • 117
  • 7

2 Answers2

3

There is no strict need to use a regex (regular expression) in your case (requires PSv4+):

(Get-Content $home\$user\appfiles\out.txt).ForEach({ '"{0}"' -f $_ })

If you did want to use a regex:

(Get-Content $home\$user\appfiles\out.txt) -replace '^|$', '"'

Regex ^|$ matches both the start (^) and the end ($) of the input string and replaces both with a " char., effectively enclosing the input string in double quotes.


As for what you tried:

^(.*?)

just matches the very start of the string (^), and nothing else, given that .*? - due to using the non-greedy duplication symbol ? - matches nothing else.

Therefore, replacing what matched with " only placed a " at the start of the input string, not also at the end.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

You can use regex to match both:

  • The beginning of the line ^(.*?)
  • OR |
  • The End of the line $

I.e. ^(.*?)|$

$Flist = Get-Content "$home\$user\appfiles\out.txt"
$Flist | %{$_ -replace '^(.*?)|$', '"'}
mklement0
  • 382,024
  • 64
  • 607
  • 775
HAL9256
  • 12,384
  • 1
  • 34
  • 46