Click to See Complete Forum and Search --> : getting substring in a script


gamblor01
01-12-2005, 01:39 PM
Hey this should be fairly easy (I would hope) but let's say I have a string in shell. Suppose I do an ls -A1 and I have all of the files in some directory. And then I find one that I specifically want, and then let's say I want to get the last 6 characters in that string. I tried cutting on a character that I knew would always exist due to our naming structure (namely, 3) and it just removed everything AFTER 3 (i.e. the remaining 5 characters). Anyone know how to do this? There's no nice substring() function like the substring() method in Java is there?

mrBen
01-12-2005, 01:52 PM
This should do the trick:


mrben@hobbes:/usr/share$ lets=abcdefghijklmnopqrstuvwxyz
mrben@hobbes:/usr/share$ echo $lets
abcdefghijklmnopqrstuvwxyz
mrben@hobbes:/usr/share$ echo ${lets: -8}
stuvwxyz
mrben@hobbes:/usr/share$


note that it's curly brackets, and you _must_ have the space between the : and the minus sign.

See also http://www.tldp.org/LDP/abs/html/string-manipulation.html

ph34r
01-12-2005, 02:00 PM
Also, take a look at the man page or --help option for cut. It should be able to do what you want.

gamblor01
01-12-2005, 02:18 PM
wo0t! Thanks guys. That works like a champ Ben.


How about one more question....

Is it possible to echo out a different character to the screen when reading input? If I just use something like "read answer" it echoes all of their key strokes to the screen. But suppose I wanted to echo * for every keystroke, but save their input to a variable in the script. Can I do that?

mrBen
01-12-2005, 03:17 PM
See http://db.ilug-bom.org.in/Documentation/abs-guide/system.html#SECRETPW

The first example just turns the echo off, but the second also looks into keypress detection, so you could probably set this to echo * every time a key is pressed until the key is <return>

It's worth reading the advanced bash scripting guide, which will have many of your answers.

gamblor01
01-13-2005, 02:49 PM
I guess it might be worth the read, but typically I don't even write shell scripts that much. I just figure it's easier to do what I can, and then just ask whenever I have a question. However, the project that I just completed at work (and got a bonus for...woo hoo!) was a set of several shell scripts that will set up, patch, and test our weekly builds. So far it's still a bit primitive, but it will get better. Thanks for the help though Ben. I'll check the advanced scripting guide more thoroughly next time. I actually searched it before posting that question (that's why it was an edit in my last post). I did try...but I promise I'll try harder next time. :) Thanks again.