Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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? Thank you in advance!

share|improve this question
    
Unfortunately I still have this error message : "./script_max_path.sh: 15: ./script_max_path.sh: Bad substitution" –  user3581976 Jul 13 at 13:40

5 Answers 5

up vote 7 down vote accepted

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 bash, ${t:(-2)} is legal as a substring expansion but is probably not what you want, since it returns the substring starting at a position 2 characters in from the end (i.e. it removes the first character of the string).

share|improve this answer

With bash, you can do:

${var::-1}

Example:

$ a=123
$ echo ${a::-1}
12
share|improve this answer
    
This works for bash version 4.2-alpha and above, too bad the version I have access to is earlier. :-/ –  h.j.k. Jul 14 at 3:46

for removing the last n characters from a line that makes no use of sed OR awk:

> echo lkj | rev | cut -c (n+1)- | rev

so for example you can delete the last character one character using this:

> echo lkj | rev | cut -c 2- | rev

> lk

from rev manpage:

DESCRIPTION
The rev utility copies the specified files to the standard output, reversing the order of characters in every line. If no files are speci- fied, the standard input is read.

UPDATE:

if you don't know the length of the string, try:

$ x="lkj"
$ echo "${x%?}"
lk
share|improve this answer
    
Thank you for your response! The problem is that I don't know the size of the string, and are you sure that there isn't an easier way to do it? –  user3581976 Jul 13 at 13:53
    
see Updates @user3581976 –  Networker Jul 13 at 14:01
t=lkj
echo ${t:0:${#t}-1}

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, dash isn't able to parse even

echo ${t:0:$(expr ${#t} - 1)}

For example, on Ubuntu, /bin/sh is dash

share|improve this answer

It is easy enough to do using regular expression:

n=2
echo "lkj" | sed "s/\(.*\).\{$n\}/\1/"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.