Bash script tip, cutting from variables

Ok, here is a quick tip that has come in handy quite a few times in my days writing shell scripts, for example in bash. Let’s say, for whatever reason, you need to chop off the end of a string (like a variable). Chopping the beginning is easy, just use the cut command, but in order to chop the end you have to know how long the string is so you can tell it where to start. In this example, we are going to us the wc command to figure out how long the string is, and then subtract 1 to cut the last character. You can subtract however many you want depending on how many characters you want to cut. Check it out …

First, we need a string. Let’s set a variable to be some fun text like so:

myvar="I need some text heree"

Uh oh, we spelled here wrong! We need to chop that extra e off of the end. Well, first we have to figure out how long this is. Yes, we could count it by hand and hard set the length, but work with me. What if we are processing hundreds or thousands of items and we have varying lengths? Yeah, I thought so. Use the wc command to determine the length of the string like this:

length=`echo -n $myvar | wc -c`

Now we know how long it is, notice how I made sure we skipped the line break (the -n) as we echo’d the variable. So let’s take that number and roll it back by one so we start out cut at the right place:

length=$[length-1]

Now, let’s cut that string!

newvar=`echo -n $myvar | cut -c -${length}`

That should be it, let’s print it out the check …

echo $newvar

You should get this:

I need some text here

Let’s see the whole script together:

#!/bin/bash
myvar="I need some text heree"
length=`echo -n $myvar | wc -c`
length=$[length-1]
newvar=`echo -n $myvar | cut -c -${length}`
echo $newvar

There you have it, a simple and easy way to chop the end off of strings. Enjoy!

Tell me what you are thinking?