This is actually pretty easy in PowerShell :
function Number-Lines($name) { Get-Content $name | ForEach-Object { $i = 1 } { "{0:000}. {1}" -f $i++,$_ } }
What I'm doing here is getting the contents of the file, this will return a String[] , over which I repeat with ForEach-Object and apply the format string using the -f operator. The result simply drops out of the pipeline as another String[] , which can be redirected to the file if necessary.
You can shorten it a bit by using aliases:
gc .\someFile.txt | %{$i=1}{ "{0:000}. {1}" -f $i++,$_ }
but I will not recommend this for function definition.
You want to consider using two passes, although constructing an on-the-fly format string to accommodate more lines. If there are 1500 lines {0:000} , then it will not be enough to get a neatly aligned output.
As for the language that is best suited for such tasks, you can look at factors such as
- brevity of code (Perl will be hard to beat there, especially that one-line in another answer)
- readability and maintainability of the code
- Accessibility tools (Perl and Python are not installed by default on Windows (PowerShell only with Windows 7), so deployment can be difficult.)
In light of the last point, you might even be better off using cmd for this task. The code is similarly pretty simple:
@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&goto :eof if %1 LSS 100 set lz=0%1&goto :eof set lz=%1&goto :eof goto :eof
This suggests, of course, that it should work somewhere else than your own machine. If not, use whatever suits you :-)
source share