Archive for the ·

bash

· Category...

don’t let the regex slash get you down

no comments

This is quick, but important for anyone who has to deal with regular expressions occasionally.

Sometimes I see regular expression search-and-replace lines that look like this, often from developers I consider far more advanced than me.

/\/\/root\/\/path\/node/\/\/root2\/\/path\/node

Remember: in nearly all regex implementations, you can swap out the slash for any one-character keyword.  If you’re working with URLs and file paths, this is a must if you want to avoid too much slash escaping.

Compare this to the previous expression:

s#//root//path/node#//root2//path/node

Much more readable!  Whichever character you choose (I like # because I rarely use it, but : is an easy-to-type option), just place it right after the ‘s’.  Use the same character between the expression search and result, and at the end if you’re adding optional flags.  This works in most programming & scripting languages, and tools like sed.

better, simpler searching and scripting with bash globstar

no comments

Do you use bash 4.0 or newer?  (You probably do.  Type ‘bash –version’ in your terminal to find out).

If so, you could be living a better life.

Globstar is a feature not typically enabled, but present in bash 4+, and it allows you to do more easily select files in bash, using a double star **.

For example, if you want to every .text file, in all subdirectories, you no longer even need to use the find command.

ls **/*.text

The ** here will traverse any number of directories, not just the current directory.  Here’s another very useful, easy to remember example.  Ever want to find a line of text somewhere in a huge pile of files, but you know some part of the file name?  You can do a recursive grep to easily find it, without some abstruse find command.

grep -r needle **/*haystack*

To begin using globstar, you need to enable it.  It should be the default, if you ask me, but enabling is simple.  From the terminal, type:

shopt -s globstar

You’ll probably want to add that line to your ~/.bashrc file, too, so it’s enabled every time you open a terminal or login.

Happy Globbing!