2

Have a list of usernames, they are formatted in one of two ways:

John Smith

John.Smith

I would like to get just the last name from each line in a text file.

I'm guessing I have to use a -replace or -remove command, just not sure how to format the regex.

I have this:

$source = "path\to\name\list.txt"

$final = "path\to\final\output.txt"

(Get-Content $source -Raw) -replace "^.\.|^."", "" | Set-Content $final

but it's not working.

0

2 Answers 2

1

Use

^[^\s.]+[\s.]+

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^\s.]+                  any character except: whitespace (\n, \r,
                           \t, \f, and " "), '.' (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  [\s.]+                   any character of: whitespace (\n, \r, \t,
                           \f, and " "), '.' (1 or more times
                           (matching the most amount possible))

Another way is also possible:

^.*[\s.]

See another proof.

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  [\s.]                    any character of: whitespace (\n, \r, \t,
                           \f, and " "), '.'
Sign up to request clarification or add additional context in comments.

Comments

0

I would simply use -split on whitespace (\s) or dot, take the last element of the resulting array.

Get-Content -Path $source | ForEach-Object {($_.Trim() -split '[\s.]')[-1]} | Set-Content -Path $final

Comments

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.