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.
foo_first.txt
foo_second.txt
foo_third.txt

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.