lud57
lud57

Reputation: 1

Powershell replace escape

I wish I could change a character string replacing the first space by semicolons:

Ex:

drwxrwxrwx 2 tot toto 4096 Dec 11 12:34 fdf fdfd

I would like something like this:

drwxrwxrwx;2;tot;toto;4096;Dec;11;12:34;fdf fdfd

Upvotes: 0

Views: 94

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200393

Use a callback function to replace the spaces after the first 8 elements of a line:

PS C:\> $callback = { $args[0] -replace ' +', ';' }
PS C:\> $re = [regex]'^(\S+ +){8}'
PS C:\> $str = 'drwxrwxrwx 2 tot toto 4096 Dec 11 12:34 fdf fdfd'
PS C:\> $re.Replace($str, $callback)
drwxrwxrwx;2;tot;toto;4096;Dec;11;12:34;fdf fdfd
PS C:\> $str = 'drwxrwxrwx 2 tot toto 4096 Dec 11 12:34 a b c d e'
PS C:\> $re.Replace($str, $callback)
drwxrwxrwx;2;tot;toto;4096;Dec;11;12:34;a b c d e

Upvotes: 0

mjolinor
mjolinor

Reputation: 68321

One possibility:

$string = 'drwxrwxrwx 2 tot toto 4096 Dec 11 12:34 fdf fdfd'
$string -split ' ',9 -join ';'

drwxrwxrwx;2;tot;toto;4096;Dec;11;12:34;fdf fdfd

or using the string split method:

$string = 'drwxrwxrwx 2 tot toto 4096 Dec 11 12:34 fdf fdfd'
$string.split(' ',9) -join ';'

drwxrwxrwx;2;tot;toto;4096;Dec;11;12:34;fdf fdfd

Upvotes: 1

Related Questions