简体   繁体   English

使用PowerShell通过从行首匹配模式从csv文件中提取文本行

[英]Extracting line of text from csv file with PowerShell by matching a pattern at the beginning of the line

I have a CSV file that I need to extract a specific pattern that occurs at the beginning of a line such as: 我有一个CSV文件,我需要提取出现在行开头的特定模式,例如:

Line of text: 文字行:

"555555","A",John"

This works: 这有效:

Get-Content $CsvFile | Select-String '^"555555"'

This does not: 这不是:

$idnum = "555555"
Get-Content $CsvFile | Select-String '^"$idnum"'

How do I extract the line when the string is assigned to a variable? 将字符串分配给变量时,如何提取行?

The single-quote in powershell is a literal. powershell中的单引号是一个文字。 So in the second, you're explicitly looking to match "$idnum" . 因此,在第二个示例中 ,您将明确地查找匹配“ $ idnum” Because you've got double-quotes in your data you'll need to work around them. 因为您的数据中有双引号,所以您需要解决它们。

Options You can build up double-quotes to get around this 选项您可以建立双引号来解决此问题

Get-Content $CsvFile | Select-String "^""$idnum"""

Or you can format in a string replacement like this: 或者,您可以使用以下格式替换字符串:

Get-Content $CsvFile | Select-String ('^"{0}"' -f $idnum)

Or you can update $idnum to include the double quotes and then the select-string call is much easier to read 或者,您可以更新$ idnum以包括双引号,然后选择字符串调用将更容易阅读

$idnum = '"555555"'
Get-Content $CsvFile | Select-String "^$idnum"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM