Click to See Complete Forum and Search --> : BASH: Removing last howevermany characters of a string


Gaxus
07-25-2003, 08:44 AM
Is there a something I can use in a bash script that will allow me to pipe in a string and have it output that string yet with a specified number of characters from the end of it removed?

EG:


z="The magic string"

echo $z
echo $z $(echo $z | ultra-cool-command 3)


output:

The magic string
The magic string The magic str

z0mbix
07-25-2003, 08:54 AM
look into 'cut':


#!/bin/sh

z="The magic string"

echo $z
echo $z $(echo $z | cut -c0-13)

Gaxus
07-25-2003, 09:11 AM
Thanks, however the length of the string in question will vary, so I'm looking for something where you don't need to specifiy a range, yet just the number of characters it needs to remove from the end of the string.

Unless there is a way to find out the length of the string as well?

Strogian
07-25-2003, 10:38 AM
echo ${z%???}

That would do it for you. Or, you could do something like this:

echo z | sed 's/.\{3\}$//'

(EDIT: had to make 2 corrections to the sed command ;))

Gaxus
07-25-2003, 10:47 AM
Thanks! :cool:

chrism01
07-25-2003, 11:26 AM
echo ${#var}

gives length of var

Gaxus
07-25-2003, 04:13 PM
Thanks for that as well! :D

So I guess another way of doing it would be:


echo $(echo $z | cut -c 0-$(expr ${#z} - 3 ))


Also...

could someone tell me what the difference between

$()

and

${}

is?

I think I'm getting a little confused. :confused:

Strogian
07-25-2003, 05:15 PM
$(echo hi), the same as `echo hi` -- bash replaces it with the output of the command "echo hi"

${bob} is the same thing as $bob, but it clearly defines where the name begins and ends. (i.e. you could do ${bob}oo, but it wouldn't be the same as $boboo)

There are also some extensions to ${}. You can read about all this stuff in the bash manpage.

x_Ray
07-25-2003, 10:37 PM
z="The magic string"

echo ${z:0:${#z}-3}
The magic str

Gaxus
07-26-2003, 04:31 AM
Holy moly :D That's a lot easier on the eyes to look at than the cut one.

Although {#z} should be ${#z}.


.... so many ways to skin a cat :cool:

x_Ray
07-26-2003, 01:54 PM
Originally posted by Gaxus

Although {#z} should be ${#z}.


Doh! Corrected it now, thanks.:)