Hari
Hari

Reputation: 11

Convert 2 columns file into 1 column

I have a text file with 2 columns and any number of lines (100 or more):

data1 data2  
data3 data4

I want to transform it to 1 column like this:

data1  
data2  
data3  
data4

In unix I could have done it with for loop and awk, but getting confused being very new to PowerShell.

Upvotes: 1

Views: 147

Answers (3)

Gajendra D Ambi
Gajendra D Ambi

Reputation: 4233

$textfile = "path/sourcefile" #path and name of the source text file
$newfile = 'newfile.txt' #name of the new text file
New-Item -ItemType file -Name $newfile #a new text file will be created from wherever you are running this script from if you have the script saved and named, else it will be created in the c drive.
$textfile = Get-Content $textfile #source text file being red and stored into a variable
foreach ($line in $textfile) {
$datas = $line.split(' ') | where { $_.length -gt 1 } #each line in the text file is being split and spaces being excluded
foreach ($data in $datas)
    { Add-Content $newfile $data } #columns being merged, this will work with multiple columns which are separated by a space

Upvotes: 0

Esperento57
Esperento57

Reputation: 17472

#Solution 1, get data with delimiter and remove blanck line and carriage return
get-content "C:\temp\test\test1.txt" -delimiter " " | where {$_ -ne " "} |  foreach {$_ -replace "`n", ""}

#Solution 2, import-csv with delimiter and print 2 columns C1 and C2
import-csv "C:\temp\test\test1.txt" -Delimiter " " -Header C1, C2 | foreach {$_.C1;$_.C2}

#Solution 3, variante of solution 2
get-content "C:\temp\test\test1.txt" | ConvertFrom-Csv -Delimiter " " -Header C1, C2 | %{$_.C1;$_.C2}

#Solution 4, variante of solution 3 but with convertfrom-string (autocomun P1 and P2 are builded)
get-content "C:\temp\test\test1.txt" | ConvertFrom-String -Delimiter " " | %{$_.P1;$_.P2}

#Solution 5 with split every row (proposed by TessellatingHeckler )
get-content "C:\temp\test\test1.txt" | foreach {-split $_ }

Upvotes: 1

TessellatingHeckler
TessellatingHeckler

Reputation: 29023

# Read lines,  loop each line with the variable name $_
Get-Content c:\wherever\input.txt | ForEach-Object {

    -split $_     # unary split breaks on whitespace
                  # pieces go down the pipeline

} | Set-Content c:\wherever\output.txt -Encoding UTF8   # save them to a file

or in the shell, for brevity:

-split(gc 1.txt)|sc 2.txt -En utf8

Upvotes: 3

Related Questions