Thursday, March 22, 2012

Trimming Trailing Whitespace in Powershell

I needed to remove the trailing spaces from each line in a text file. I came up with this.

    $lines = (Get-Content $filename);
    $lines |
        ForEach-Object { $_.TrimEnd(); } |
        Out-File $_ -Encoding Ascii;

Notice that I specify the encoding on the Out-File cmdlet. This should be set to whatever the encoding of the file is. If that option is omitted, the file is output as double-byte Unicode which is almost never what you'd want.

Tuesday, February 21, 2012

What I learnt playing "vimgolf: replacing each line of a block selection"

The substitute command can use delimiters other than /.

For example, let's say you want to replace the path a/b/c with d/e in the current line.

You could use the usual / as the delimiter and escape the forward slashes in the pattern and replacement like this:
:s/a\/b\/c/d\/e/

But it would be much easier to another delimiter, say ; and avoid the escaping like this:
:s;a/b/c;d/e;

See :help E146 for more detail

Saturday, January 28, 2012

Stashing Changes in Mercurial

Stashing means setting aside changes to a working directory without commiting them.

It's useful if, for example, you're adding a feature to one of your projects when you find a bug that you want to fix immediately. You don't want to not mix the fix up with your feature code and you aren't ready to commit and start a new changeset. The solution is to stash your changes, code the bug fix and commit it and then unstash them to resume working on the feature.

Recipe

hg diff | Out-File -Encoding ascii stash.patch
hg update -C
# other stuff...
hg import --no-commit stash.patch

Explanation

Output of hg diff is a unified diff which we save to file. hg update -C, of course, removes the changes from the working directly. Be careful that you don't accidentally lose work when you're doing this! After other stuff, we use the import command to unstash the changes.

Comparison to Other Methods

There are extensions for stashing but, in my experience, they don't work very well.

mq is used for this as well but that procedure is unnecessarily complicated if you don't normally use mq.