2

I'm trying to find a way to grab a specific line from a string based on line number.

For instance, I want to pull whatever is in line 19.

From what I understand, I could do this with Get-Content and -Index if I was pulling from a file. Is there an alternative when working with variables instead of files?

1
  • Does the variable contain just one big multi-line string, or multiple strings? Commented Jun 4, 2018 at 21:48

2 Answers 2

4

Assuming a single, multi-line string $str as the input, and $lineNo as the 1-based line number to extract:

($str -split '\r?\n')[$lineNo - 1]
  • -split '\r?\n' splits the input string into an array of lines.

    • Note: Regex \r?\n is designed to match both Windows-style CRLF newlines and Unix-style LF-only newlines.
      If your multi-line string literal were to be defined in your source code, for instance, the newline style of the source code's file determines the string's.
  • Then [$lineNo - 1] accesses the line of interest; given that line numbers are 1-based but array indices are 0-based, - 1 must be applied to the line number.


Example:

$str = @'
line 1
line 2
line 3
line 4
line 5
'@

$lineNo = 3

($str -split '\r?\n')[$lineNo - 1]  # -> 'line 3'
Sign up to request clarification or add additional context in comments.

1 Comment

@drummerof13: Glad to hear it was helpful; my pleasure.
1

Depends how your string/variable is constructed and what delimiters your data has.

Maybe these examples inspire you...

$var1 = @(
'one'
'two'
'three'
)

$var2 = "four,five,six"

$var3 = @'
seven
eight
nine
'@

# array
$var1[1]

# string with delimeter
$var2.Split(',')[1]

# here string like raw file with CRLF as delim
$var3.Split("`r`n")[1]

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.