Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIX remove characters from variable

Tags:

linux

unix

sh

sed

I want to remove the last 4 charachters from an input string and then use it in a sed command. But i can't get it to work properly

newversion is an input parameter and it is set to: 5.5.5-dev. I want to remove -dev from the input parameter.

What i have tried:

version=${$newversion::-4}
sed -i "s|\(<<some name i defined>>/$imagename:\)\([^\n]*\)|\1$version|" docker-compose.yml

The error:

Bad substitution

like image 505
legopiraat Avatar asked Dec 25 '22 09:12

legopiraat


2 Answers

sed is overkill for this problem. To remove -dev from the end of a string in any POSIX shell, use

version=${newversion%-dev}

or more generally

version=${newversion%-???}  # Remove the final - and the next 3 characters

or even

version=${newversion%-*}  # Remove the final - and anything after it.

If you were using bash (which you do not appear to be), your first attempt was close; you simply have an extra $. It should be

version=${newversion::-4}

although a negative value in that position requires bash 4. In bash 3, you need to compute the value using the length of the string:

version=${newversion::${#newversion}-4}
like image 200
chepner Avatar answered Jan 06 '23 06:01

chepner


If $newversion contains "5.5.5-dev". i.e newversion="5.5.5-dev"

Why don't you try sed to remove -dev.

version=`echo $newversion | sed "s/-dev//g"`

or if you are using bash

version=`sed "s/-dev//g"<<<$newversion`
like image 41
sudheesh shetty Avatar answered Jan 06 '23 05:01

sudheesh shetty