Delete the last character of a string using string manipulation in shell script
With bash
4.2 and above, you can do:
${var::-1}
Example:
$ a=123
$ echo "${a::-1}"
12
Notice that for older bash
( for example, bash 3.2.5
on OS X), you should leave spaces between and after colons:
${var: : -1}
In a POSIX shell, the syntax ${t:-2}
means something different - it expands to the value of t
if t
is set and non null, and otherwise to the value 2
. To trim a single character by parameter expansion, the syntax you probably want is ${t%?}
Note that in ksh93
, bash
or zsh
, ${t:(-2)}
or ${t: -2}
(note the space) are legal as a substring expansion but are probably not what you want, since they return the substring starting at a position 2 characters in from the end (i.e. it removes the first character i
of the string ijk
).
See the Shell Parameter Expansion section of the Bash Reference Manual for more info:
- Bash Reference Manual – Shell Parameter Expansion
Using sed it should be as fast as
sed 's/.$//'
Your single echo is then echo ljk | sed 's/.$//'
.
Using this, the 1-line string could be any size.