Search code examples
powershellselect-stringselect-object

Add index number to list of results of `Select-String`


I need to search for a term in a file and display an index in the search results so that referencing is easy.

The command in bash would be:

cat <file> | grep 'Table: ' | cat -n

What I have so far in Powershell:

Get-Content <file> | Select-String 'Table: ' | Select-Object -Property LineNumber, Line

Unfortunately, I didn't realize that LineNumber gives the actual line in the file and not the index in the results list.

How can I translate the bash command into its Powershell equivalent?


Solution

  • Indeed, the .Line property of the objects output by Select-Object indicates the line number of each match in a given input file.

    PowerShell has no direct equivalent of cat -n (prepending a 1-based index to all input lines on output), but it's not hard to roll your own using the ForEach-Object cmdlet:

    $i = 0
    Get-Content file.txt | Select-String 'Table: ' | ForEach-Object {
      "{0,6}`t{1}" -f ++$i, $_.Line
    }
    

    The above uses -f, the format operator, to left-space-pad to 6 characters (,6) the first RHS operand ({0}), which is the (incremented) index, ++$i, followed by a tab character (`t) and the second RHS operand ({1}), which is the input line at hand ($_.Line).