2

I want to ls -name a folder and wrap the result between the quotes`. However the result make an extra quote after.

> (ls -name) -replace '(.*)', '"$1"'
"apple"""
"orange"""
"dog"""
"cat"""

Why is that?

Ooker
  • 1,969
  • 4
  • 28
  • 58
  • 1
    Probably because [`.*` doesn't match everything](https://www.regular-expressions.info/dot.html) but does match an empty string. What about: `(.+)`? – iRon Aug 14 '22 at 16:18
  • 1
    You can see at [this demo](https://regex101.com/r/IWidse/1), that it matches a 2nd time at the end of the string. I'm not quite sure why this happens. On a side note, you can remove the capture group and use `$0` in the substitution to represent whole match: `(ls -name) -replace '.+', '"$0"'` – zett42 Aug 14 '22 at 16:52
  • C# and PowerShell use the same .NET RegEx engine so the linked answer applies to PowerShell as well. – zett42 Aug 14 '22 at 17:15
  • That is odd. Alternatively `ls -name | % { "\`"$_\`"" }` – js2010 Aug 14 '22 at 19:00
  • 2
    Another one that works: `(ls -name) -replace '^|$', '"'`. This replaces both the beginning (`^`) and the end (`$`) of the input string by a single `"`. – zett42 Aug 14 '22 at 20:00

0 Answers0