我一直在尝试一些Powershell命令,但无法通过此命令。我对此有些陌生,所以请和我一起裸露。
我有多个文件-命名为File1,File2,File3,依此类推。每个文件具有以下格式的多行:“一些文本,一些更多的文本,更多的文本”
我需要执行以下操作:1.在每个文件的每一行中,删除“,”之前的文本的第一部分。因此,“一些文本,更多文本,更多文本”应变为“一些更多文本,更多文本”
我在这里签出了类似的请求:Powershell - Delete Everything After a Delimiter - In Text files Found in Folder
但是仍然无法使事情进展。这是我在请求的第一部分中尝试的内容:
Foreach ($file in (Get-Childitem $path))
{
(Get-Content $file.fullname -Delimiter ',')[1] |
Set-Content "$OutPath\$($file.name)"
}
这将删除第一个“,”之前和第二个“,”之后的文本-我需要将所有文本保留在第一个“,”之后。
谢谢
使用-split运算符,您可以在其上指定结果中需要多少部分。
类似这样的东西:
$Path = 'D:\Original' # the path where the original files are
$OutPath = 'D:\Updated' # the path where the updated files should go
# check if the output path exists. If not, create it
if (!(Test-Path -Path $OutPath -PathType Container)) {
$null = New-Item -Path $OutPath -ItemType Directory
}
foreach ($file in (Get-Childitem -Path $path -File)) {
(Get-Content $file.FullName) | ForEach-Object {
# the $_ automatic variable represents one line for each iteration.
# output the updated line. The cleanest way I think is to use the -f Format operator.
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-5.1#format-operator--f
'{0},{1}' -f $file.Name, ($_ -split ',', 2)[-1]
} |
Set-Content -Path (Join-Path -Path $OutPath -ChildPath $file.Name)
}
希望有所帮助
另一种方法可能是使用正则表达式和-replace
运算符:
Foreach ($file in (Get-Childitem $path)) {
$Content = Get-Content -Path $file.fullname
$NewContent =
foreach ($line in $Content) {
$line -replace '^.*?(?=,)', $file.BaseName
}
$NewContent | Out-File -FilePath "$OutPath\$($file.name)"
}