Search code examples
regexstringpowershellexport-to-csv

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.


Solution

  • 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".