3

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.

1 Answer 1

8

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".
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer ! :) Would you mind explaining the role of those characters in your regex? Thanks!
Terrific! Thank you sir! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.