Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is actually pretty easy in <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="nofollow noreferrer">PowerShell</a>:</p> <pre><code>function Number-Lines($name) { Get-Content $name | ForEach-Object { $i = 1 } { "{0:000}. {1}" -f $i++,$_ } } </code></pre> <p>What I'm doing here is getting the contents of the file, this will return a <code>String[]</code>, over which I iterate with <code>ForEach-Object</code> and apply a format string using the <code>-f</code> operator. The result just drops out of the pipeline as another <code>String[]</code> which can be redirected to a file if needed.</p> <p>You can shorten it a little by using aliases:</p> <pre><code>gc .\someFile.txt | %{$i=1}{ "{0:000}. {1}" -f $i++,$_ } </code></pre> <p>but I won't recommend that for a function definition.</p> <p>You way want to consider using two passes, though and constructing the format string on the fly to accommodate for larger numbers of lines. If there are 1500 lines <code>{0:000}</code> it won't be sufficient anymore to get neatly aligned output.</p> <p>As for which language is best for such tasks, you might look at factors such as</p> <ul> <li>conciseness of code (Perl will be hard to beat there, especially that one-liner in another answer)</li> <li>readability and maintainability of code</li> <li>availability of the tools (Perl and Python aren't installed on Windows by default (PowerShell only since Windows 7), so deployment might be hindered.)</li> </ul> <p>In the light of the last point you might even be better off using <code>cmd</code> for this task. The code is similarly pretty simple:</p> <pre><code>@echo off setlocal set line=1 for /f "delims=" %%l in (%1) do call :process %%l endlocal goto :eof :process call :lz %line% echo %lz%. %* set /a line+=1 goto :eof :lz if %1 LSS 10 set lz=00%1&amp;goto :eof if %1 LSS 100 set lz=0%1&amp;goto :eof set lz=%1&amp;goto :eof goto :eof </code></pre> <p>That assumes, of course, that it has to run somewhere else than your own machine. If not, then use whatever fits your needs :-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload