Monday, October 04, 2010

Techie Tidbits: Beef up the CMD Prompt

Are you a frequent Cygwin user and/or often ask yourself "Why is the CMD prompt so crap?!"? If so, you'll probably be interested to know how you can inject some or possibly all of that Linux/Bash goodness into your CMD prompt.
1st, Install Cygwin if you haven't already done so
2nd, Extend Your PATH
Create a bin (short for binary, but conventionally the home for anything executable) folder in your user directory, then add this directory to your PATH variable: Win+Pause > Advanced Settings > Environment Variables, probably best to add it to User variables for <You>
3rd, Create Your Associations
I've made an associations.cmd file in my personal bin directory with the following contents:
@echo off

assoc .sh=BashScript
ftype BashScript="C:\Cygwin\bin\env.exe" "CYGWIN=nodosfilewarning" "/bin/bash" -l "%%1" %%*

assoc .pl=PerlScript
ftype PerlScript="C:\Cygwin\bin\env.exe" "CYGWIN=nodosfilewarning" "/bin/perl" "%%1" %%*

assoc .py=PythonScript
ftype PythonScript="C:\Dev\Python\2.6(x86)\python.exe" "%%1" %%*

assoc .rb=RubyScript
ftype RubyScript="C:\Dev\Ruby\1.8.6\bin\ruby.exe" "%%1" %%*
Clearly I have Python and Ruby installed on Windows - if you don't omit the last and second to last command pairs. If you have installed the Perl package in Cygwin (which I recommend you do), then the second pair of commands wires that up. Now run this CMD file.
4th, Extend Your PATHEXT
Follow the instructions in step 2, but instead of changing the PATH variable, add the Bash, Python and Perl script file extensions (SH, PY and PL, respectively) to the semi-colon separated PATHEXT variable

This now allows you to run any Bash, Python or Perl script from anywhere on the CMD Prompt, JOY!

A Perl Example
Create prename.pl in your personal bin directory with the following contents:
#!/usr/bin/perl -w

$op = shift or die "Usage: rename expr [files]\n";
chomp(@ARGV = ) unless @ARGV;
for (@ARGV) {
    $was = $_;
    eval $op;
    die $@ if $@;
    rename($was,$_) unless $was eq $_;
}

Now if you have a file called file_123.txt and you wanted to rename it to file_abc.txt, you could run the following in a CMD Prompt:

prename "s,\d+,abc," file*

No comments: