使用Powershell解析逗号分隔的文件 [英] Parsing a comma separated file using powershell
问题描述
我有一个文本文件,其中包含几行,每行都是一个逗号分隔的字符串.每行的格式为:
I have a text file which contains several lines, each of which is a comma separated string. The format of each line is:
<Name, Value, Bitness, OSType>
Bitness
和OSType
是可选的.
例如文件可以是这样的:
For example the file can be like this:
Name1, Value1, X64, Windows7
Name2, Value2, X86, XP
Name3, Value3, X64, XP
Name4, Value3, , Windows7
Name4, Value3, X64 /*Note that no comma follows X64 */
....
....
我想将每一行解析为4个变量并对其执行一些操作.这是我使用的PowerShell脚本.
I want to parse each line into 4 variables and perform some operation on it. This is the PowerShell script that I use..
Get-Content $inputFile | ForEach-Object {
$Line = $_;
$_var = "";
$_val = "";
$_bitness = "";
$_ostype = "";
$envVarArr = $Line.Split(",");
For($i=0; $i -lt $envVarArr.Length; $i++) {
Switch ($i) {
0 {$_var = $envVarArr[$i].Trim();}
1 {$_val = $envVarArr[$i].Trim();}
2 {$_bitness = $envVarArr[$i].Trim();}
3 {$_ostype = $envVarArr[$i].Trim();}
}
}
//perform some operation using the 4 temporary variables
}
但是,我想知道是否可以在PowerShell中使用正则表达式来执行此操作.您可以提供执行此操作的示例代码吗?请注意,每行中的第3和第4个值可以选择为空.
However, I wanted to know if it is possible to do this using regex in PowerShell. Would you please provide sample code for doing that? Note that the 3rd and 4th values in each line can be optionally empty.
推荐答案
您可以使用Import-Csv
cmdlet的-Header
参数为导入的文件指定备用列标题行:
You can specify an alternate column header row for the imported file file with the -Header
parameter of the Import-Csv
cmdlet:
Import-Csv .\test.txt -Header Col1,Col2,Bitness,OSType
这篇关于使用Powershell解析逗号分隔的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!