Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first matching character in string in PowerShell

In the following string,

apache:x:48:48:Apache:/var/www:/sbin/nologin

how could I replace the first colon (and this one only) with a comma so I would get the following string?

apache,x:48:48:Apache:/var/www:/sbin/nologin

Also, the code has to support a file with multiple lines and replace the first comma in each line only.

like image 354
Bluz Avatar asked Jun 17 '26 22:06

Bluz


1 Answers

Use a regular expression:

PS C:\> $s = 'apache:x:48:48:Apache:/var/www:/sbin/nologin'
PS C:\> $s -replace '^(.*?):(.*)','$1,$2'
apache,x:48:48:Apache:/var/www:/sbin/nologin

Regexp breakdown:

  • ^(.*?):: shortest match between the beginning of the string and a colon (i.e. the text before the first colon).
  • (.*): the remainder of the string (i.e. everything after the first colon).

The parantheses group the subexpressions, so they can be referenced in the replacement string as $1 and $2.

Further explanation:

  • ^ matches the beginning of a string.
  • .* matches any number of characters (. ⇒ any character, * ⇒ zero or more times).
  • .*? does the same, but gives the shortest match (?) instead of the longest match. This is called a "non-greedy match".
like image 55
Ansgar Wiechers Avatar answered Jun 20 '26 12:06

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!