How to Extract Substring in Bash
Let’s say you have a bash variable:
x=abc123defAnd 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 most/all UNIX-like systems, including Mac OS X.
Note: I derived this solution from http://hintsforums.macworld.com/showthread.php?t=101414.