PowerShell将index [0]指向字符串的第一个实例,将index [1]指向第二个实例,依此类推,直到完成 [英] PowerShell index[0] to the first instance of the string, index[1] to the second instance and so on till finished
本文介绍了PowerShell将index [0]指向字符串的第一个实例,将index [1]指向第二个实例,依此类推,直到完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,将LINE2 1243替换为LINE2 1,因为它位于test.txt的第1行.
For example, replace LINE2 1243 with LINE2 1 because it is on line 1 of test.txt.
# Find the line number:
$lines = sls "LINE2" test.txt | Select-Object -ExpandProperty LineNumber
test.txt:
abc LINE2 1243
lmn LINE2 1250
xyz LINE2 1255
使用:
gc test.txt | % { $_ -replace "LINE2.*", "LINE2 $lines" }
我得到:
abc LINE2 1 2 3
lmn LINE2 1 2 3
xyz LINE2 1 2 3
如何为字符串的第一个实例提供index [0],仅提供index [0],为第二个实例提供index [1],依此类推,直到完成.
How do I supply index[0], and only index[0], to the first instance of the string, index[1] to the second instance and so on till finished.
用另一种方式做:
foreach ($line in $lines){
gc test.txt | % { $_ -replace "LINE2.*", "LINE2 $line" }
}
我得到:
abc LINE2 1
lmn LINE2 1
xyz LINE2 1
abc LINE2 2
lmn LINE2 2
xyz LINE2 2
abc LINE2 3
lmn LINE2 3
xyz LINE2 3
如何仅将字符串的第一个实例获取index[0]
,依此类推.
How do I get index[0]
to only the first instance of the string and so on.
推荐答案
您可以使用带有索引的for循环来实现此目的(如果我理解正确的话;-)
You could use a for loop with an index to achieve this (If I got you right) ;-)
$lines = Select-String "LINE2" -Path C:\sample\test.txt | Select-Object -ExpandProperty LineNumber
Get-Content -Path C:\sample\test.txt -OutVariable Content
for ($index = 0; $index -lt $lines.count; $index++) {
$Content[$index] -replace "LINE2.*", "LINE2 $($lines[$index])"
}
输出:
abc LINE2 1
lmn LINE2 2
xyz LINE2 3
这篇关于PowerShell将index [0]指向字符串的第一个实例,将index [1]指向第二个实例,依此类推,直到完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文