I would like to delete the last character of a string, I tried this little script :
#! /bin/sh
t="lkj"
t=${t:-2}
echo $t
but it prints "lkj", what I am doing wrong?
I would like to delete the last character of a string, I tried this little script :
but it prints "lkj", what I am doing wrong? |
||||
|
In a POSIX shell, the syntax Note that in See the Shell Parameter Expansion section of the Bash Reference Manual for more info: |
|||||||||
|
With
Example:
Notice that for older
|
|||||||||||||||||||||
|
for removing the last
so for example you can delete the last character
from
UPDATE: if you don't know the length of the string, try:
|
|||||||||
|
You get a substring from 0 to the string length -1. Note however that this substraction is bash specific, and won't work on other shells. For instance,
For example, on Ubuntu, |
||||
|
A few options depending on the shell:
|
|||||||||
|
You can also use
But unfortunately some versions of |
|||
|
Using sed it should be as fast as
Your single echo is then |
|||||
|
It is easy enough to do using regular expression:
|
|||
|
Thank you SteelDriver and Networker! if you don't know the length of the string, try:
|
||||
|
Some refinements. To remove more than one character, you can add multiple question marks. For example, to remove the last two characters from the variable:
|
||||
|
The most portable, and shortest, answer is almost certainly:
This works in bash, sh, ash, dash, busybox/ash, zsh, ksh, etc. It works by using old-school shell parameter expansion. Specifically, the See "Remove Smallest Suffix Pattern" here for a (much) more detailed explanation and more background. Also see the docs for your shell (eg: As a side note, if you wanted to remove the first character instead, you would use Also worth noting is that both Understanding parameter expansions, or at least knowing about their existence and knowing how to look them up, is incredibly useful for writing and deciphering shell scripts of many flavors. Parameter expansions often look like arcane shell voodoo to many people because... well... they are arcane shell voodoo (although pretty well documented if you know to look for "parameter expansion"). Definitely good to have in the tool belt when you're stuck in a shell, though. |
|||
|
In ksh:
|
||||
|