1

I have a CSV file that I need to extract a specific pattern that occurs at the beginning of a line such as:

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?

1
  • 3
    (Get-Content $CsvFile) -match "^`"$idnum". With that said, please take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution. What do you need the extracted line for? Commented Feb 28, 2019 at 21:12

1 Answer 1

5

The single-quote in powershell is a literal. So in the second, you're explicitly looking to match "$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 = '"555555"'
Get-Content $CsvFile | Select-String "^$idnum"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.