我有一个包含2列和任意行数(100或更多)的文本文件:
data1 data2
data3 data4
我想将它转换为1列,如下所示:
data1
data2
data3
data4
在unix中,我可以使用for循环和awk完成它,但是对PowerShell来说是一个非常新的。
答案 0 :(得分:3)
# 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
或在shell中,为简洁起见:
-split(gc 1.txt)|sc 2.txt -En utf8
答案 1 :(得分:1)
key
答案 2 :(得分:0)
$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