Wednesday, April 7, 2010

one-liner: mount the current directory to a temporary top-level drive letter

Suppose you're doing command line stuff in some ridiculously deep folder, e.g. C:\some path\to some\ridiculously deep\folder\way down\below a reasonable\level>, so the default command prompt pushes way over to the right edge of the screen, and any output containing the wraps 3 times in the window, and it's just really hard to read:

The following one-liner will "substitute" a temporary drive x: for the current path, effectively mounting C:\some path\to some\ridiculously deep\folder\way down\below a reasonable\level> as x:\

for /f "tokens=*" %i in ('cd') do @subst x: "%i"

Delete the temporary drive with the command subst /d x:

Tuesday, April 6, 2010

Substituting characters inline

Use the following technique to make character substitutions on the fly from DOS command results.

Given a file listing with underscores in the file names, e.g.

This is ugly, but it works. Start a new command shell with delayed variable expansion option cmd /v, then run the following one-liner, e.g. to replace the underscores with spaces:

C:\>for /f %i in ('dir /b') do @set x=%i & echo !x:_= !

The result will be:
foo first.txt
foo second.txt
foo third.txt

The first trick, delayed variable expansion, is enabled by starting a new command shell with the /v option. This lets you set and change a variable's value at runtime by surrounding the variable with bangs ! instead of percents %. Normally, the default no immediate variable expansion would not update the x variable each time dir /b returns a line. Only the last value set to x is echoed each time:

foo third.txt
foo third.txt
foo third.txt

The second trick, character substitution, is set by !x:_= !.

You can substitute other characters, e.g. !x:abc=def! would turn abcxyz.txt into defxyz.txt