locked
Powershell Check number of words in Line-SOLVED RRS feed

  • Question

  • i have variable $name

    it contains John Doe string

    I want to check if line contains 2 or more that 2 words

    If it contains 2 words (John Doe) create new variable which will consist from first word of First name and append Last name

    (JDoe), if $body variable contains more than 2 words (John JR Doe) create this variable: JJRDoe (append First Name Character) with other Words

    I manged only to extract first word

    $fname = $name.split(" ")[0]

    $lname = $name.split(" ")[1]

    so i cat get John and can get last name

    But no idea how to check if there are 2 or three words



    • Edited by Dragan979 Friday, May 3, 2019 7:34 AM
    Tuesday, April 30, 2019 11:39 AM

Answers

  • if($name.split('  ').Count -eq 2){
         $firstname,$lastname = $name -split '\s+'
    }


    \_(ツ)_/


    Tuesday, April 30, 2019 12:44 PM
  • Try this:

    # variable containg name
    $Name = "Joe JR Bloggs"
    # split the name based on a space
    $aName = $Name.Split(' ')
    # get only the first character of firstname
    $NewName = $aName[0][0]
    # then select remaining names regerdless of amount
    $lName = $aName | Select-Object -skip 1
    # put it all back together
    ForEach($sName in $lName){
        $NewName += $sName
    }
    # new name :)
    $NewName

    Tuesday, April 30, 2019 3:50 PM

All replies

  • if($name.split('  ').Count -eq 2){
         $firstname,$lastname = $name -split '\s+'
    }


    \_(ツ)_/


    Tuesday, April 30, 2019 12:44 PM
  • Try this:

    # variable containg name
    $Name = "Joe JR Bloggs"
    # split the name based on a space
    $aName = $Name.Split(' ')
    # get only the first character of firstname
    $NewName = $aName[0][0]
    # then select remaining names regerdless of amount
    $lName = $aName | Select-Object -skip 1
    # put it all back together
    ForEach($sName in $lName){
        $NewName += $sName
    }
    # new name :)
    $NewName

    Tuesday, April 30, 2019 3:50 PM
  • thanks @jrv, that's what i needed !
    Friday, May 3, 2019 7:08 AM
  • thanks @jrv, that's what i needed !

    Please mark the answer that answered your question.

    \_(ツ)_/

    Friday, May 3, 2019 7:47 AM
  • both replies helped me
    Monday, May 6, 2019 7:10 AM