1

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?

Khalid Hussain
  • 345
  • 4
  • 16
  • We can do this in bash in powershell. `cat | grep 'Table: ' | cat -n`. `get-content | select-string 'Table: ' | (foreach ($line in $(Get-Content -Path test.sh)){$count++; echo "$count $line"})` – Nico Nekoru Jun 16 '20 at 01:30

2 Answers2

2

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).

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Just use WSL:

bash -c "cat <file> | grep 'Table: ' | cat -n"

This will run the bash code in powershell. For a true powershell option you could do this:

foreach ($line in $(Get-Content -Path <filepath> | Select-String 'Table: ')){
  $count++
  echo "$count $line"
}
Nico Nekoru
  • 2,840
  • 2
  • 17
  • 38