Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find character position and update file name

What function might I use to find a character position in a string using PowerShell 2.0?

i.e I would use CHARINDEX or PATINDEX if using SQL Server.

I looked at using the Select-String cmdlet, but it doesn't seem to do what I need it to do.

Ultimately I'm looking to find a "_" character in a file name and strip off everything to the following "." .

Example file name 237801_201011221155.xml

like image 244
Pixelated Avatar asked Feb 23 '11 19:02

Pixelated


2 Answers

The string is a .NET string so you can use .NET methods. In your case:

$index = "The string".IndexOf(" ")

will return 3, which is the first occurrence of space in the string. For more information see: http://msdn.microsoft.com/en-us/library/system.string.aspx

For your need try something like:

$s.SubString($s.IndexOf("_") + 1, $s.LastIndexOf(".") - $s.IndexOf("_") - 1)

Or you could use regexps:

if ($s -Match '(_)(.*)(\.)[^.]*$') {  $matches[2] }

(has to be adjusted depending on exactly what you need).

like image 101
Anders Zommarin Avatar answered Sep 18 '22 14:09

Anders Zommarin


If you split the filename on underscore and dot, you get an array of 3 strings. Join the first and third string, i.e. with index 0 and 2

$x = '237801_201011221155.xml' 
( $x.split('_.')[0] , $x.split('_.')[2] ) -join '.' 

Another way to do the same thing:

'237801_201011221155.xml'.split('_.')[0,2] -join '.'
like image 22
mosaic Avatar answered Sep 21 '22 14:09

mosaic