Reputation: 11
I need to extract columns from one file and join them in another file. I used this code to select the columns that I need:
$original_path = 'C:\Users\leticia.araujo\Downloads\Arquivo Buffer\Arquivo teste'
$files = Get-ChildItem $original_path
ForEach($file in $files) {
$pathFile = $original_path + '\' + $file.Name
$SegundaColuna = Get-Content -Path $pathFile | Foreach {"$(($_ -split ',')[3..3])"}
$TerceiraColuna = Get-Content -Path $pathFile | Foreach {"$(($_ -split ':')[3..3])"}
$QuartaColuna = Get-Content -Path $pathFile | Foreach {"$(($_ -split ',')[10..10])"}
}
When I try to put these in a txt using
'Add-Content $pathFile $SegundaColuna,$TerceiraColuna,$QuartaColuna'
I got, but in the file the columns are not next to each other. they are under each other. Example: I need they are like this:
1 a
2 b
3 c
But they are like this:
1
2
3
a
b
c
Upvotes: 1
Views: 132
Reputation: 437090
Focusing on a single file inside your foreach
loop:
Since the values to join come from the same lines of a given file, read that file line by line:
Get-Content -Path $pathFile | # Read the file line by line.
ForEach-Object { # Process each line.
($_ -split ',')[3],
($_ -split ':')[3],
($_ -split ',')[10] -join ' ' # Output the column values joined with a space.
} |
Set-Content out.txt
If you need to merge columns across all your input files and create a single output file, replace the foreach
loop with a single pipeline:
Get-ChildItem $original_path |
Get-Content |
ForEach-Object {
($_ -split ',')[3],
($_ -split ':')[3],
($_ -split ',')[10] -join ' '
} |
Set-Content out.txt
Upvotes: 2