0

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

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
lud57
  • 1
  • You want to replace all spaces except the last one? – Micky Balladelli Dec 12 '14 at 09:09
  • Your example looks like you want to replace every space except for the last one with semicolons. Is that really what you want to do? Because that would put semicolons between the elements of a date field, and might also put semicolons in file names when they have more than one space in them. Please take a step back and describe what you ultimately want to achieve by doing this. – Ansgar Wiechers Dec 12 '14 at 09:11
  • I try to put a semicolon to date fields.I try to recovered the folder name , even if it contains spaces. " fdf fdfd " is the name of my test directory with space – lud57 Dec 12 '14 at 09:16

2 Answers2

1

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
mjolinor
  • 66,130
  • 7
  • 114
  • 135
0

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
Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Thanks, it's great: $re = [regex]'^(\S+ ){8}'; $line = $line -replace '^(\S+ ){8}', ' ' | % {$re.Replace($_, { $args[0] -replace ' ', ';' })}; – lud57 Dec 12 '14 at 09:43
  • @lud57 That would remove everything except the file name. If that's what you want, simply running `$line -replace '^(\S+ ){8}'` would be a lot simpler. – Ansgar Wiechers Dec 12 '14 at 10:41
  • sorry before the code was not good: $re = [regex]'^(\S+ ){8}'; $line = $line -replace '\s+', ' ' | % {$re.Replace($_, { $args[0] -replace ' ', ';' })}; – lud57 Dec 12 '14 at 15:32
  • Here the initial chain: drwxrwxrwx 2 toto toto 258048 Dec 10 15:07 folder0 drwxrwxrwx 2 toto toto 520192 Dec 11 12:48 folder1 -rw-rw-rw- 1 toto toto 289352 Dec 10 14:18 a.jpj drwxrwxrwx 2 toto toto 4096 Dec 11 12:34 fdf fdfd – lud57 Dec 12 '14 at 15:35
  • @lud57 You don't need to collapse consecutive spaces in a preparatory step. I updated my answer to take care of that. – Ansgar Wiechers Dec 12 '14 at 17:53