One of the great things about Unix/Linux is that there is usually more than one way to do something so you get to choose the one that best suits your purposes.
bash
You can crop characters from the end of a string without having to load another command if your shell is a reasonably modern version of bash:
Code:
string="elephant" echo "${string:0:${#string}-4}"
That’s probably a bit hard to read. Here is the same thing broken into its two parts:
Code:
string="elephant" len=${#string}-4 echo "${string:0:$len}"
Here is another, simpler way to do it in bash:
Code:
string="elephant" echo "${string%????}"
head
Probably the simplest and easiest way to do it is using head.
NOTE: I don’t think this works with the cut-down version of head in busybox.
Code:
string="elephant" echo -n "$string" | head -c-4
awk
You can do it with awk, which is a bit ridiculous, though nicely general purpose and very easy to read:
Code:
string="elephant" echo -n "$string" | gawk '{print substr($0,1,length()-4)}'
Notice that I used the -n option for echo which prevents it appending a newline character, otherwise it would look like only 3 characters were chopped.
sed
I’m a bit of a fan of sed though.
This is fastest:
Code:
string="elephant" echo "$string" | sed 's/....$//'
This is slower but less tedious if you have lots of characters to remove:
Code:
string="elephant" echo "$string" | sed 's/.\{4\}$//'
cut I love this even though it is nuts:
Code:
string="elephant" echo "$string" | rev | cut -c 5- | rev
If you want to use cut without reversing the string you have to find out the length of the string first then subtract the number of characters you want cropped. This is a hassle, but can still be done fairly easily:
Code:
string="elephant" let len=${#string}-4 echo "$string" | cut -c 1-$len
or harder to read, but more concisely:
Code:
string="elephant" echo "$string" | cut -c 1-$((${#string}-4))
Note that for all the examples using an external command you don’t really need echo. You can use ‘here’ redirection like this:
Code:
head -c-5 <<<"$string"
Last edited by miriam-e; 07-28-2014 at 03:57 AM. Reason: added code tags & fixed head example & added more examples
liked this article?
- only together we can create a truly free world
- plz support dwaves to keep it up & running!
- (yes the info on the internet is (mostly) free but beer is still not free (still have to work on that))
- really really hate advertisement
- contribute: whenever a solution was found, blog about it for others to find!
- talk about, recommend & link to this blog and articles
- thanks to all who contribute!