|
-
BASH: Removing last howevermany characters of a string
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:
Code:
z="The magic string"
echo $z
echo $z $(echo $z | ultra-cool-command 3)
output:
Code:
The magic string
The magic string The magic str
-
look into 'cut':
Code:
#!/bin/sh
z="The magic string"
echo $z
echo $z $(echo $z | cut -c0-13)
Last edited by z0mbix; 07-25-2003 at 09:09 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?
Last edited by Gaxus; 07-25-2003 at 09:16 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 )
Last edited by Strogian; 07-25-2003 at 10:41 AM.
-
Thanks!
-
echo ${#var}
gives length of var
Cheers
Chris
-
Thanks for that as well! 
So I guess another way of doing it would be:
Code:
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.
-
$(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.
-
z="The magic string"
echo ${z:0:${#z}-3}
The magic str
Last edited by x_Ray; 07-26-2003 at 01:54 PM.
-
Holy moly 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
Last edited by Gaxus; 07-26-2003 at 04:33 AM.
-
Originally posted by Gaxus
Although {#z} should be ${#z}.
Doh! Corrected it now, thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|