Extracting pattern in a text file

This topic contains 4 replies, has 3 voices, and was last updated by Profile photo of ravilobo ravilobo 3 years, 11 months ago.

  • Author
    Posts
  • #8925
    Profile photo of ravilobo
    ravilobo
    Participant

    I have a file that has following data. How to extract only the letters till ‘_’ in each line?

    Xy678_dkashdkahd
    Xy_dkashdkahd
    Xy678sga_dkashdkahd
    9999_dkashdkahd

  • #8926
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Hmm. Probably a lot of approaches.

    $lines = get-content file.txt
    foreach ($line in $lines) {
     $pieces = $line -split '_'
     write-output $pieces[0]
    }
    

    Might be one approach.

  • #8927
    Profile photo of ravilobo
    ravilobo
    Participant

    Great! Thank you Sir! I was banging my head to get this in a single line using PATTERN/MATCH etc. But your solution works. Thank you much.

  • #8935
    Profile photo of Rob Campbell
    Rob Campbell
    Participant

    If you wat a single line solution:
    (get-content file.txt) -replace '^([^_]+)_.+','$1'

  • #8942
    Profile photo of ravilobo
    ravilobo
    Participant

    Thank you Rob! This is what I was looking for at the first place. I know some regex. So I could actually understand it. Thank you both.

You must be logged in to reply to this topic.