Archive for June, 2011

How to Extract Substring in Bash

Let’s say you have a bash variable:

x=abc123def

And you want to get everything in the substring that comes before “def.” You can use awk to do this, but it’s a bit “awk”ward (though very flexible and powerful in general). An easy solution is to do the following:

y=${x%def*}
echo $y # Should print "abc123"

This approach should work on [...] Read more »

Splitting a String into Array and Accessing Contents by Index in bash

Say you have a variable in a bash script that looks like this:

x="abc_123_def"

Now say you want to split this variable into an array. The character you will use to split it is the underscore (_). So you want to end up with an array of three objects: abc, 123, and def. Then you want to [...] Read more »

Sorting String Values That Contain Numbers in Python

If you have a list of String objects in Python and want to sort them but treat any numeric values accordingly, it will not work with the regular sort function in Python. So if you have the following list:

x = ["3", "1", "10", "2"]

You will get the following if you sort and print it:

print sorted(x) [...] Read more »

How to Scale a Vector of Numbers to One

Let’s say you have a vector of numbers: 1, 2, and 5. And let’s say you have another vector of numbers: 3, 4, 9. These vectors have different ranges, but you believe they actually should have the same range. This scenario probably sounds strange, but it can happen, for example, in cases where genetic data [...] Read more »