我试着写一个脚本,它的工作原理如下:
我的输入是一个文本文件,有8行8列,填充了值0
或1
,每个空格字符分别分隔列。
我需要检查每一行中的第四个数字,并输出false
(如果是0
)和true
(如果是1
)。
目前我的代码如下所示:
param($fname)
$rows = (Get-Content $fname)
for ($i=0;$i -lt $rows.Length;$i++)
{
if ($rows[$i][6] -eq 1)
{
Write-Host "true"
}
if ($rows[$i][6] -ne 1)
{
Write-Host "false"
}
}
所以我使用[$i][6]
,因为我得到的是第四个数字,表示作为分隔符的空格的数量。
我检查并认为它是完美的,但不知何故,它说false
的每一行,但当我Write-Host
$rows[0][6]
,它是1
。
发布于 2016-12-08 15:49:33
tl;博士
# Create sample input file, with values of interest in 4th field
# (0-based field index 3).
@'
0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
'@ > file
foreach ($line in (Get-Content file)) {
$fields = -split $line
if ($fields[3] -eq '1') {
"true"
} else {
"false"
}
}
产量:
false
true
在原始代码中有许多微妙之处需要考虑,但是上面的代码:
awk
运算符提供了一种更多的-like方法。-split ...
返回的所有字段都是字符串,因此与字符串文本'1'
进行比较,但是通常PowerShell为您执行许多幕后转换魔术:使用上面的代码--与您自己的代码不同--使用1
也是可行的。至于,为什么您的方法失败了?
6
)返回[char]
实例。-eq
)的表达式的LHS (左侧),它在应用运算符之前确定RHS (右侧)在必要时将被强制到哪种类型:- `([char] '1') -eq 1 # !! $false`
- Coercing the (implied) `[int]` type of RHS `1` to the LHS type `[char]` yields Unicode _codepoint_ `U+0001`, i.e., a _control character_ rather than the "ASCII" digit '`1`', which is why the comparison fails.
- @PetSerAl's helpful, but cryptic suggestion (in a comment on the question) to use `'1'[0]` rather than `1` as the RHS solves the problem in this particular case, because `'1'[0]` returns `1` as a `[char]` instance, but the solution doesn't generalize to _multi-character_ field values.
- `'1' -eq 1 # $true; same as: ([string] 1) -eq 1 or ([string] 1) -eq '1'`
- Converting integer `1` to a _string_ indeed is the same as `'1'`.
发布于 2016-12-08 17:00:50
这个脚本用矩阵文件中的适当值填充一个真正的2d数组,但是输出不合适。
$Array = New-Object "bool[,]" 8,8
[int]$i=0 ; [int]$j=0
get-content $fname|foreach{ foreach ($b in ($_ -split(' '))) {
"{0},{1}={2}" -f $i,$j,($b -eq 0)
$Array[$i,$j] = ($b -eq 0)
$j++}
$j=0; $i++}
https://stackoverflow.com/questions/41050250
复制相似问题