Find character position and update file name

前端 未结 5 1257
离开以前
离开以前 2021-01-07 22:01

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 looke

相关标签:
5条回答
  • 2021-01-07 22:27

    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 '.'
    
    0 讨论(0)
  • 2021-01-07 22:29

    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).

    0 讨论(0)
  • I know this thread is a bit old but, I was looking for something similar and could not find it. Here's what I came up with. I create a string object using the .Net String class to expose all the methods normally found if using C#

    [System.String]$myString
     $myString = "237801_201011221155.xml"
     $startPos = $myString.LastIndexOf("_") + 1 # Do not include the "_" character
     $subString = $myString.Substring($startPos,$myString.Length - $startPos)
    

    Result: 201011221155.xml

    0 讨论(0)
  • 2021-01-07 22:43

    If you're working with actual files (as opposed to some sort of string data), how about the following?

    $files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }
    

    (or use _.+$ if you want to cut everything from the first underscore.)

    0 讨论(0)
  • 2021-01-07 22:43

    If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

     $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"
    

    asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

     $text.IndexOf("E=")
    

    7 - this is the "FIND" command for Powershell

     $text.substring(10,5)
    

    C1234 - this is the "MID" command for Powershell

     $text.substring($text.IndexOf("E=")+2,8)
    

    PC123456 - tada it has found and cut our text

    -RavonTUS

    0 讨论(0)
提交回复
热议问题