Powershell 如何在txt文件的特定行中查找字符串的所有实例的位置?
假设我有一个.txt文件,其中包含多行日期/时间: 2020年5月5日上午5:45:45 2020年10月5日下午12:30:03 我想找到一行中所有斜线的位置,然后继续下一行 因此,对于第一行,我希望它返回值: 13 对于第二行,我想: 14 我该怎么做呢 我目前有:Powershell 如何在txt文件的特定行中查找字符串的所有实例的位置?,powershell,substring,Powershell,Substring,假设我有一个.txt文件,其中包含多行日期/时间: 2020年5月5日上午5:45:45 2020年10月5日下午12:30:03 我想找到一行中所有斜线的位置,然后继续下一行 因此,对于第一行,我希望它返回值: 13 对于第二行,我想: 14 我该怎么做呢 我目前有: $firstslashpos = Get-Content .\Documents\LoggedDates.txt | ForEach-Object{ $_.IndexOf("/")} 但这只给出了每行的第一个“/”,
$firstslashpos = Get-Content .\Documents\LoggedDates.txt | ForEach-Object{
$_.IndexOf("/")}
但这只给出了每行的第一个“/”,并同时给出了所有行的结果。我需要它来循环,在这里我可以计算出每行的每个“/”之间的空间 对不起,如果我说得不好。你确实可以使用这个方法
function Find-SubstringIndex
{
param(
[string]$InputString,
[string]$Substring
)
$indices = @()
# start at position zero
$offset = 0
# Keep calling IndexOf() to find the next occurrence of the substring
# stop when IndexOf() returns -1
while(($i = $InputString.IndexOf($Substring, $offset)) -ne -1){
# Keep track of the index at which the substring was found
$indices += $i
# Update the offset, we'll want to start searching for the next index _after_ this one
$offset = $i + $Substring.Length
}
}
现在您可以执行以下操作:
Get Content listOfDates.txt | ForEach对象{
$index=Find SubstringIndex-InputString$\子字符串'/'
写入主机“在索引处找到斜杠:$($index-join',')”
}
使用一种简洁的解决方案,它在给定字符串中查找给定字符串的所有匹配项,并返回匹配对象的集合,该集合还指示每个匹配项的索引(字符位置):
# Create a sample file.
@'
5/5/2020 5:45:45 AM
5/10/2020 12:30:03 PM
'@ > sample.txt
Get-Content sample.txt | ForEach-Object {
# Get the indices of all '/' instances.
$indices = [regex]::Matches($_, '/').Index
# Output them as a list (string), separated with spaces.
"$indices"
}
上述收益率:
1 3
1 4
注:
- 完全不包含
实例的输入行将导致空行/
- 如果要将索引输出为数组(集合),而不是字符串,请使用
作为,[regex]::匹配($_,“/”).Index
脚本块中的唯一语句;一元形式的ForEach对象
,确保(通过临时辅助数组)方法调用返回的集合作为一个整体输出。如果省略,
,则索引将逐个输出,从而在变量中收集时形成平面数组,
ForEach对象
在LoggedDates.txt
行上循环。您需要在ForEach对象
中使用另一个循环来循环每一行($\ucode>)的字符。当前,我在($I-$string.InexOf($substring,$offset))-ne-1)为空值时收到了一个有关节的错误。
为空值。我怀疑这可能是因为在我的文件中,顶部大约有五行不包含“/”?我该如何解决这个问题?@justmayo你有-
而不是=
和InexOf
而不是IndexOf
。对不起,我想这只是我评论中的一个输入错误。我在另一台机器上做代码,这样就不会被复制了。我认为问题在于函数参数名为$InputString
,但是被搜索的变量名为$string
。是的,这是一个拼写错误,现在已修复