Search code examples
powershellselect-string

powershell | select-string pattern + line unter the pattern


is there a way to select a string pattern, and get also the line after the pattern.

my metadata look like :

"t": "d",
      "n": "00001212",
        "22.06.2031",
        "",
        "",
        "batman",

my codeline looks like:

$contentNameFolder= $content__ | Select-String -Pattern '"n": * ' 

my output looks like :

"n": "00001212",

what i want to get is:

"n": "00001212",
        "22.06.2031",

i was trying to add into my code -context 1,2 or something like that but this dont worked for me.


Solution

  • You have been close. As you have already seen Select-String has the -Context parameter which allows you to specify the lines before and after the match that should be displayed.

    If you pass in an array with two integers the first number determines the lines before the match and the second number the lines after the match (See: Select-String | Microsoft Docs).

    If you don't want any lines before the match to display, set the first integer to 0.

    $contentNameFolder= $content__ | Select-String -Pattern '"n": * ' -Context 0,1
    

    In your example this will give you the following result:

    "n": "00001212",
            "22.06.2031",