Extracting pattern in a text file

This topic contains 4 replies, has 3 voices, and was last updated by  ravilobo 4 years, 2 months ago.

  • Author
    Posts
  • #8925

    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

    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

    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

    Rob Campbell
    Participant

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

  • #8942

    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.