I have multiple files. Let's name them File1
, File2
, File3
and so on.
Each files has multiple lines in the format:
Some text,some more text,more text
I need to do the following:
In each line of each file, remove the first part of the text before the ",". So "Some text,some more text,more text" should become "some more text,more text"
Prefix the respective file name to each line with a comma : "some more text,more text" - becomes "File1,some more text,more text"
I checked out a similar request here : Powershell - Delete Everything After a Delimiter - In Text files Found in Folder
But still unable to get things rolling. This is what I tried for the first part of the request:
Foreach ($file in (Get-Childitem $path))
{
(Get-Content $file.fullname -Delimiter ',')[1] |
Set-Content "$OutPath\$($file.name)"
}
This removes the text before the first "," and after the second "," - I need to keep all text after the first ",".
Use the -split operator, on which you can specify how many parts you want in the result.
Something like this:
$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://learn.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)
}
Hope that helps