How to do this in PowerShell? Or : what language to use for file and string manipulation? How to do this in PowerShell? Or : what language to use for file and string manipulation? powershell powershell

How to do this in PowerShell? Or : what language to use for file and string manipulation?


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 iterate with ForEach-Object and apply a format string using the -f operator. The result just drops out of the pipeline as another String[] which can be redirected to a file if needed.

You can shorten it a little by using aliases:

gc .\someFile.txt | %{$i=1}{ "{0:000}. {1}" -f $i++,$_ }

but I won't recommend that for a function definition.

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 {0:000} it won't be sufficient anymore to get neatly aligned output.

As for which language is best for such tasks, you might look at factors such as

  • conciseness of code (Perl will be hard to beat there, especially that one-liner in another answer)
  • readability and maintainability of code
  • availability of the tools (Perl and Python aren't installed on Windows by default (PowerShell only since Windows 7), so deployment might be hindered.)

In the light of the last point you might even be better off using cmd for this task. The code is similarly pretty simple:

@echo offsetlocalset line=1for /f "delims=" %%l in (%1) do call :process %%lendlocalgoto :eof:processcall :lz %line%echo %lz%. %*set /a line+=1goto :eof:lzif %1 LSS 10 set lz=00%1&goto :eofif %1 LSS 100 set lz=0%1&goto :eofset lz=%1&goto :eofgoto :eof

That assumes, of course, that it has to run somewhere else than your own machine. If not, then use whatever fits your needs :-)


perl -i -ne 'printf("00%d. %s",$.,$_)' your-filename-here

You may want %03d instead.


It isn't what you wanted, but please recall findstr.exe(and find.exe) at times...

findstr /n ".*" filenamefind "" /v /n filename