删除整个 txt 文件的“,”之前的文本 - 通过文件夹递归

Removing text before ',' for the entire txt file - recursively through the folder

我有多个文件。我们将它们命名为 File1File2File3 等。 每个文件都有多行,格式为:

Some text,some more text,more text

我需要做以下事情:

  1. 在每个文件的每一行中,删除“,”之前的文本的第一部分。 所以 "Some text,some more text,more text" 应该变成 "some more text,more text"

  2. 用逗号为每行加上相应的文件名前缀: "some more text,more text" - 变成 "File1,some more text,more text"

我在这里查看了类似的请求:

但还是无法让事情顺利进行。这是我在请求的第一部分尝试的:

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)"
}