[英]How to edit line in text file via powershell script
I'm new in powershell world and of courser I'm stuck.我是 powershell 世界的新手,当然我被困住了。 I'm trying to iterate through text file and to find some lines and to edit it.
我正在尝试遍历文本文件并找到一些行并对其进行编辑。 Cannot use simple replace flag because I have some other logic involved.
不能使用简单的替换标志,因为我还涉及一些其他逻辑。
So my approach is like this:所以我的方法是这样的:
Get-ChildItem -Path $JsonsFolderPath -File -Recurse -Filter *.json | ForEach-Object {}
With this line I iterate through all json's in $JsonsFolderPath
folder.通过这一行,我遍历了
$JsonsFolderPath
文件夹中的所有 json。
Now, hot to iterate thorugh all line of a file and do some custom logic?现在,很想遍历文件的所有行并执行一些自定义逻辑吗?
I've tried something like this: (this goes inside upper foreach)我试过这样的事情:(这进入上层foreach)
$content = Get-Content -Path $_.FullName |
ForEach-Object {
if(//something)
{
return ModifyFunction($_)
}
else
{
return $_ // do not modify
}
} | Set-Content -Path $_.FullName
How to approach this?如何解决这个问题?
you can loop over the lines in powershell你可以遍历 powershell 中的行
foreach($line in [System.IO.File]::ReadLines(<file_path>)) {
$line.Replace('<original_string>', '<new_string>')
}
you can also add conditions or a counter to only edit specific line or at a specific line number.您还可以添加条件或计数器以仅编辑特定行或特定行号。 For the specific line number, just declare a counter variable before the for-loop and a target line number.
对于具体的行号,只需在for循环之前声明一个计数器变量和一个目标行号即可。 Increment the counter by 1 in the for loop and check, whether $counter -eq $targetLineNumber before you replace the contents in that line.
在 for 循环中将计数器加 1 并检查 $counter -eq $targetLineNumber 是否替换该行中的内容。
If you know the exact string, you want to replace, then i refer you to this link:如果你知道确切的字符串,你想替换,那么我推荐你到这个链接:
https://shellgeek.com/powershell-replace-line-in-file/ https://shellgeek.com/powershell-replace-line-in-file/
Cheers.干杯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.