I want to cat
a file and output the line number of each line it outputs.
However, in PowerShell, cat
outputs an array. Hence the question effectively becomes: How do I print the index of each item while it's being output to the console…?
I tried something like this:
$k = cat foo.js
$k | foreach { $index = $k.IndexOf($_) + 1; write "$index : $_"; } | more
It gave me some weird results. Some line numbers repeated. What is an elegant and more reliable way to do this?
Best Answer
I want to cat a file and output the line number of each line it outputs.
Use the following command:
As pointed out in the comments:
write-output
instead ofwrite-host
as this allows further processing of the output.echo
is an alias forwrite-output
So the above command becomes:
Example output:
Example output from Cygwin
cat -n
for comparison: