Remove the first or last characters in a shell script

By

Learn how to remove the first or last n characters from a variable in a shell script using cut, and the rev trick to trim characters off the end.

~~~

To remove the first n characters from a variable in a shell script, pipe it to cut. To remove the last n characters, reverse the string with rev, cut from the front, and reverse it back.

While working on a Bash / Fish script I had the need to remove the last n characters from a string, and it took way longer to figure out than I wanted. Here’s what I found.

How to remove the first n characters

cut -c selects characters by position, starting from 1. cut -c10- prints from the 10th character to the end:

#!/bin/sh
original="my original string"
result=$(echo "$original" | cut -c10-)
echo "$result" #al string

Notice the numbering. Printing from character 10 means you removed the first 9 characters, not 10. To remove the first 3 characters, start at character 4:

result=$(echo "$original" | cut -c4-)
echo "$result" #original string

How to remove the last n characters

cut can’t count from the end of the string. The trick is rev, which reverses its input. Reverse the string, cut characters off the front, then reverse it back:

#!/bin/sh
original="my original string"
result=$(echo "$original" | rev | cut -c10- | rev)
echo "$result" #my origin

Same off-by-one rule applies: cut -c10- on the reversed string removes the last 9 characters.

An alternative without external commands

The shell can do this on its own, with parameter expansion. # strips a pattern from the start, % strips it from the end. Each ? matches one character:

original="my original string"
echo "${original#???}" #original string
echo "${original%???}" #my original str

Here ${original#???} removes the first 3 characters and ${original%???} removes the last 3. This is POSIX, so it works in plain sh, and it doesn’t spawn any processes. The downside is you write one ? per character, so it gets unreadable for large or variable counts. That’s when I reach for cut.

Be careful with quoting

If you write echo $original without quotes, sh and Bash split the value on whitespace and echo joins the pieces back with single spaces. Any run of multiple spaces collapses into one, and your character positions shift silently.

The fix is to always quote the variable, like the examples above do: echo "$original".

Tagged: CLI · All topics
~~~

Related posts about cli: