Author Posts

July 29, 2013 at 10:25 am

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

July 29, 2013 at 10:30 am

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.

July 29, 2013 at 10:34 am

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.

July 29, 2013 at 12:01 pm

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

July 29, 2013 at 12:16 pm

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.