查找字符位置并更新文件名 [英] Find character position and update file name
问题描述
我可以使用什么函数来使用 PowerShell 2.0 查找字符串中的字符位置.
What function might I use to find a character position in a string using PowerShell 2.0.
即如果使用 SQL Server,我将使用 CHARINDEX 或 PATINDEX.
i.e I would use CHARINDEX or PATINDEX if using SQL Server.
我查看了使用 Select-String
cmdlet,但它似乎没有做我需要它做的事情.
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 "." .
示例文件名237801_201011221155.xml
最终解决方案,以下删除当前目录中所有 .xml 文件的所有字符,包括 <_> 到 <.>
Final Solution, The below strips out all characters from and including <_> to <.> for all .xml files in the current directory
Get-Childitem *.xml | Rename-Item -newname `
{ $_.name -replace $_.name.SubString($_.name.IndexOf("_"), `
$_.name.LastIndexOf(".") - $_.name.IndexOf("_") ),''}
最终会得到 237801.xml
推荐答案
该字符串是 .NET 字符串,因此您可以使用 .NET 方法.在你的情况下:
The string is a .NET string so you can use .NET methods. In your case:
$index = "The string".IndexOf(" ")
将返回 3,这是字符串中第一次出现的空格.有关详细信息,请参阅:http://msdn.microsoft.com/en-us/library/system.string.aspx
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).
这篇关于查找字符位置并更新文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!