Friday, February 4, 2011

How do I increment a value in a textfile using the regular Windows command-line?

I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a textfile with a plain number in it, and then simply call upon a small script to increment this each time I compile.

How would I go about doing this using the the regular Windows command-line?

I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated aswell.

  • It would be an new shell (but I think it is worth it), but from PowerShell it would be

    [int](get-content counter.txt) + 1 | out-file counter.txt
    
  • If you don't mind running a Microscoft Windows Based Script then this jscript will work OK. just save it as a .js file and run it from dos with "wscript c:/script.js".

    var fso, f, fileCount;
    var ForReading = 1, ForWriting = 2;   
    var filename = "c:\\testfile.txt";
    fso = new ActiveXObject("Scripting.FileSystemObject");
    
    //create file if its not found
    if (! fso.FileExists(filename))
    {
      f = fso.OpenTextFile(filename, ForWriting, true);
      f.Write("0");
      f.Close();
    }
    
    f = fso.OpenTextFile(filename, ForReading);
    fileCount = parseInt(f.ReadAll());
    
    //make sure the input is a whole number
    if (isNaN(fileCount))
    {
        fileCount = 0;  
    }
    
    fileCount = fileCount + 1;
    
    f = fso.OpenTextFile(filename, ForWriting, true);
    f.Write(fileCount);
    f.Close();
    
    From Re0sless
  • You can try a plain old batchfile.

    @echo off
    for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1
    echo %temp_counter% > counter.txt
    

    assuming the count.bat and counter.txt are located in the same directory.

    From crono
  • I'd suggest just appending the current datetime of the build to a log file.

    date >> builddates.txt
    

    That way you get a build count via the # of lines, and you may also get some interesting statistics if you can be bothered analysing the dates and times later on.

    The extra size & time to count the number of lines in the file will be insignificant unless you are doing seriously fast project iterations!

    From Tom

0 comments:

Post a Comment