powershell - 在 Powershell 的 CSV 文件数字列中查找文本数据
问题描述
我是PowerShell的新手。我试图通过找出我的数字字段中是否有任何文本值来验证我的 CSV 文件。我可以用列定义为数字。
这是我这样的源数据
ColA ColB ColC ColD
23 23 ff 100
2.30E+01 34 2.40E+01 23
df 33 ss df
34 35 36 37
我需要这样的输出(如果在任何列中找到,则只有文本值)
ColA ColC ColD
2.30E+01 ff df
df 2.40E+01
ss
我尝试了一些代码但没有得到任何结果,只得到一些输出,如下所示
System.Object[]
---------------
xxx fff' ddd 3.54E+03
...
这就是我正在尝试的
#cls
function Is-Numeric ($Value) {
return $Value -match "^[\d\.]+$"
}
$arrResult = @()
$arraycol = @()
$FileCol = @("ColA","ColB","ColC","ColD")
$dif_file_path = "C:\Users\$env:username\desktop\f2.csv"
#Importing CSVs
$dif_file = Import-Csv -Path $dif_file_path -Delimiter ","
############## Test Datatype (Is-Numeric)##########
foreach($col in $FileCol)
{
foreach ($line in $dif_file) {
$val = $line.$col
$isnum = Is-Numeric($val)
if ($isnum -eq $false) {
$arrResult += $line.$col
$arraycol += $col
}
}
}
[pscustomobject]@{$arraycol = "$arrResult"}| out-file "C:\Users\$env:username\Desktop\Errors1.csv"
####################
有人可以指导我正确的方向吗?谢谢
解决方案
你可以试试这样的
function Is-Numeric ($Value) {
return $Value -match "^[\d\.]+$"
}
$dif_file_path = "C:\Users\$env:username\desktop\f2.csv"
#Importing CSVs
$dif_file = Import-Csv -Path $dif_file_path -Delimiter ","
#$columns = $dif_file | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name'
# Use this to specify certain columns
$columns = "ColB", "ColC", "ColD"
foreach($row in $dif_file) {
foreach ($col in $columns) {
if ($col -in $columns) {
if (!(Is-Numeric $row.$col)) {
$row.$col = ""
}
}
}
}
$dif_file | Export-Csv C:\temp\formatted.txt
- 随时查找列的名称
- 查找每行中每个列的值,如果不是数字,则更改为“”
- 导出的更新文件。
推荐阅读
- angular - Add some element to a variable it will be automaticated added to another variable
- google-apps-script - 谷歌表格宏创建具有特定桶大小的直方图
- python - 有没有办法在 Python 中自动执行以下代码 - 初学者
- java - 一旦文件已经到达文本文件的末尾,如何在java中使用hasNext()从头开始扫描文件?
- r - 将字符串值转换为频率计数
- javascript - 从 json 数据创建表格视图
- javascript - jQuery .click 不适用于 jQuery 生成的按钮
- javascript - 如何在Javascript中创建一个连续日期数组
- javascript - 在带有 @emotion/core 的样式组件中使用过渡
- swiftui - 如何检查 SwiftUI 何时订阅了 ObservableObject 的已发布属性?