经过一周的尝试,我不得不问你这个。
文件输入:
DD/MM
27,28
14,21
1
15
7
12
2,15
25
此文件的每一行代表一个月,因此即使它是空的,它仍然应该计数,以便格式化可以发生。然后根据文件输入,所需的输出是:
期望的输出:
DD/MM
27/02
28/02
14/04
21/04
01/05
15/06
07/09
12/10
02/11
15/11
25/12
到目前为止我得到了什么,并坚持到这里:
#getting the content into an array and formatting the .DAT file
$lines = Get-Content $outfileBR
If ($lines[0] -eq "DD/MM") {
$HEADER = $lines[0] + $linebreak
}
If ($lines[1] -eq '') {
continue
} Else {
$BRFILE = $lines[1].SUBSTRING(0,2) + "/01" + $linebreak
$BRFILE += $lines[1].SUBSTRING(3,2) + "/01" + $linebreak
}
If ($lines[2] -eq '') {
continue
} Else {
$BRFILE2 = $lines[2].SUBSTRING(0,2) + "/02" + $linebreak
$BRFILE2 += $lines[2].SUBSTRING(3,2) + "/02" + $linebreak
}
If ($lines[3] -eq '') {
continue
} Else {
$BRFILE3 = $lines[3].SUBSTRING(0,2) + "/03" + $linebreak
$BRFILE3 += $lines[3].SUBSTRING(3,2) + "/03" + $linebreak
}
Set-Content $BRdatFile ($HEADER + $BRFILE + $BRFILE2 + $BRFILE3)
结果:
DD/MM
/01
/01
27/02
28/02
/03
/03
就像我说的,每行指的是一个月,但是如果该行是空的(如输入文件中所示),我不会在输出中显示它。但是根据我的结果,它出现在/ 01表示1月,/ 03表示行军,等等。
我做错了什么,拜托?
答案 0 :(得分:4)
非常类似于Ronald Rink'd-fens'给出的答案,我会在循环中做一个循环,但是因为我们知道文件中应该有多少行,所以我会这样做:
#Get content of input file
$FileIn = Get-Content C:\Path\To\File.txt
#Start array for output with header record
[array]$FileOut += 'DD/MM'
#Loop 12 times, once for each month
ForEach($Month in (1..12)){
#Split the relevant line, and for each entry add a line to the output file
If([string]::IsNullOrEmpty($FileIn[$Month])){Continue}
$FileIn[$Month].Split(',') | ForEach{
$FileOut += '{0}/{1}' -f $_, $Month
}
}
#Output the new file
$FileOut | Set-Content C:\Path\To\NewFile.txt
修改:我修复了2个问题。我有[1..2]应该是(1..12),并使用$_
引用而不是$Month
(无论如何都应该工作,但这是不好的形式imho)。
答案 1 :(得分:3)
在PowerShell中实现这一点就像这样简单:
"DD/MM";
$lines = Get-Content $ENV:TEMP\input.txt;
for($c = 1; $c -lt $lines.Count; $c++)
{
$line = $lines[$c];
if(!$line) { continue; }
$line.Split(',') | % { '{0:00}/{1:00}' -f [int] $_, $c }
}
27/02
28/02
14/04
21/04
01/05
15/06
07/08
12/09
02/10
15/10
25/11
修改:已修复$day
/ $_