When working on a Bash or Fish script, there may come a time when you need to remove the first or last few characters from a string variable. While this task might seem straightforward, it can sometimes take longer than expected to figure out the correct solution. In this blog post, we’ll explore how to remove the first or last characters from a variable in a shell script.
Removing the First Characters
To remove the first n characters from a string variable, you can use the cut
command in combination with command substitution. Here’s an example:
#!/bin/sh
original="my original string"
result=$(echo $original | cut -c10-) # cut first 10 characters
echo $result
In this script, we set the original
variable to the string “my original string”. Then, we use the cut
command with the -c
option to specify the characters to cut. In this case, we cut from the 10th character until the end of the string. Finally, we assign the resulting string to the result
variable and echo it.
Removing the Last Characters
Similarly, if you want to remove the last n characters from a string variable, you can use the rev
command along with cut
and command substitution. Here’s an example:
#!/bin/sh
original="my original string"
result=$(echo $original | rev | cut -c10- | rev) # cut last 10 characters
echo $result
In this script, we use rev
to reverse the string before cutting. Then, we use cut
as before, cutting from the 10th character until the end. Finally, we reverse the string again using rev
and assign the result to the result
variable.
By following these approaches, you can remove the first or last characters from a variable in a shell script. Make sure to adjust the number of characters to cut based on your specific requirement.