我在一个文本文件中有一行温度数据,我想将其转换为单个列,并使用PowerShell脚本将其保存为CSV文件。温度用逗号分隔,看起来像这样:
21,22,22,22,22,22,22,20,19,18,17,16,15,14,13,12,11,10,9,9,9,8,8,9,8,8,8,9,9,8,8,8,9,9,9,8,8,8,8,8,9,10,12,14,15,17,19,20,21,21,21,21,21,21,21,21,21,21,21,20,20,20,20,20,22,24,25,26,27,27,27,28,28,28,29,29,29,28,28,28,28,28,28,27,27,27,27,27,29,30,32,32,32,32,33,34,35,35,34,33,32,32,31,31,30,30,29,29,28,28,27,28,29,31,33,34,35,35,35,36,36,36,36,36,36,36,36,36,37,37,37,37,37,37,38,39,40,42,43,43,43,43,43,42,42,42,41,41,41,41,40,39,37,36,35,34,33,32,31,31,31,31,31,31,31,31,31,31,
我在这个论坛上尝试了几种基于搜索的方法,我认为这可能有效,但它返回一个错误:将行转置到PowerShell
中的列这是我尝试的修改后的代码,返回:错误:"输入字符串格式不正确。">
$txt = Get-Content 'C:myfile.txt' | Out-String
$txt -split '(?m)^,r?n' | ForEach-Object {
# create empty array
$row = @()
$arr = $_ -split 'r?n'
$k = 0
for ($n = 0; $n -lt $arr.Count; $n += 2) {
$i = [int]$arr[$n]
# if index from record ($i) is greater than current index ($k) append
# required number of empty fields
for ($j = $k; $j -lt $i-1; $j++) { $row += $null }
$row += $arr[$n+1]
$k = $i
}
$row -join '|'
}
这看起来应该很简单,只有一行数据。有关于如何将这一行数字转换为一列的任何建议吗?
试试这个:
# convert row to column data
$header = 'TEMPERATURE'
$values = $(Get-Content input.dat) -split ','
$header, $values | Out-File result.csv
#now test the result
Import-Csv result.csv
标题是CSV文件中的第一行(或记录)。在本例中,它是一个单词,因为只有一列。
值是输入中逗号之间的项。在这种情况下,逗号上的-split会生成一个字符串数组。注意,如果逗号是分隔符,最后一个温度之后将没有逗号。你的数据看起来不像那样,但我假设真实的数据是这样的。
然后,将头文件和数组写入文件。但是那些逗号怎么了?事实证明,对于单列CSV文件,没有逗号分隔字段。所以结果是一个简单的CSV文件。
最后,使用Import-csv对输出进行测试,以读取结果并以表格格式显示。
这不一定是最好的编码方式,但它可以帮助初学者习惯powershell。
假设我正确理解了你的意图,基于你的口头描述(不是你自己的编码尝试):
# Create simplified sample input file
@'
21,22,23,
'@ > myfile.txt
# Read the line, split it into tokens by ",", filter out empty elements
# with `-ne ''` (to ignore empty elements, such as would
# result from the trailing "," in your sample input),
# and write to an output CSV file with a column name prepended.
(Get-Content myfile.txt) -split ',' -ne '' |
ForEach-Object -Begin { 'Temperatures' } -Process { $_ } |
Set-Content out.csv
更简洁的选择,使用可扩展的(插入的)here-string:
# Note: .TrimEnd(',') removes any trailing "," from the input.
# Your sample input suggests that this is necessary.
# If there are no trailing "," chars., you can omit this call.
@"
Temperatures
$((Get-Content myfile.txt).TrimEnd(',') -split ',' -join [Environment]::NewLine)
"@ > out.csv
out.csv
则包含:
Temperatures
21
22
23