PowerShell string manipulation

This topic contains 7 replies, has 3 voices, and was last updated by  TeeStar 3 months, 3 weeks ago.

  • Author
    Posts
  • #77790

    TeeStar
    Participant

    Hi all

    I am having an issue trying to do some basic string manipulation if I have a simple string like

    $a="1234567890"

    I would like to change say the value of the sixth character regardless of the value. I can't seem to get the proper format to accomplish this.

    Any help would be appreciated.
    Thanks
    Tim

  • #77791

    Kevyn
    Participant

    Try this, where 8 is the value replacing the 6th character in the $a variable:

    $a.Replace($a[5],"8")
    
    #OR
    
    $a -Replace $a[5],"8"
    
    
  • #77794

    Kevyn
    Participant

    Note that with the .Replace() method, you can only replace the character with a single character, like in the example I gave above. Using the -Replace operator, you can replace the single character with a string.

  • #77796

    Kevyn
    Participant

    Also, the .Replace() method and -Replace operator will replace all instances of the character you're trying to replace. So, if $a = "12345678690", then if you replace the 6th character, which is a 6 in the string, all 6s will be replaced (example, with the letter 'r').

    12345678690 becomes 12345r78r90

  • #77799

    Kevyn
    Participant

    If you want to make sure you only replace that once instance of whatever is the 6th character(index = 5), then you can do the following.

    $a = $a.Substring(0,4),'CharacterOrStringYouWantToReplaceThe6thCharacterWith',$a.Substring(6,$a.Length - 6) -join ""
    
  • #77803

    Curtis Smith
    Participant

    Another option.

    $a = '1234567890'
    $a.Remove(5,1).Insert(5,"a")
    • #77805

      Kevyn
      Participant

      Good to know. 🙂

  • #77808

    TeeStar
    Participant

    Great thanks a lot guys, I appreciate it. @Curtis That one was great, it was exactly what I have been looking for.

You must be logged in to reply to this topic.