variables in ksh

I'm new to unix scripting. How would I go about pulling the first 3 characters from a variable in ksh and storing in another variable? Thanks.

Several ways, of course. One popular way is:
var2=`echo $var1 | cut -c1-3`
and some will pipe it through sed, but I prefer to use expr because it is just one command, no pipe:
var2=`expr "$var1" : "\(...\)"`

Whatever command to use, we are "nesting" the command string in back-quotes. The back-quoted command will be replaced in the command line by its output.

In ksh, I think the most efficient way (do man ksh), when you can use it:

var2=${var1#pattern} (remove one occurent from front)
var2=${var1##pattern} (remove mult occurrences from front)
var2=${var1%pattern} (remove one occurrence from end)
var2=${var1%%pattern} (remove mult occurrences from end)

But in this case, we want to remove, from the end, all but the first 3 characters, and I could not come up with an expression to represent that.

Try this:

$ var=123456
$ var=${var##???}
$ echo $var
456

Hope this helps!

Yep, that will delete the first 3 characters, but steve6368 was wanting to pull (retain) the first 3 characters into another variable.

Oops, in that case it should be :

$ var=123456
$ var=${var%%???}
$ echo $var
123

LivinFree,

What are the functionality of ## and %% ? Any more special symbols we can use ?

Thanks.

LivinFree, that will delete last 3 characters, and would retain exactly 3 only when your original variable is exactly 6 character. If your original variable is 10 characters, that solution pulls the first 7.

I could not think of a way to retain just the first 3 using that construct, as I mentioned in my first reply. The %% expression would need to represent "all but the first 3 characters".

variable=$something       # variable has some characters -- we don't know how many
rest=${variable#???}      # we removed the first 3 characters 
first3=${variable%$rest}  # now we have the first 3 characters

This works as long as the variable has at least 3 characters in it. If it has only one or two, first3 will be empty.

awesome, Perderabo. And it works embedded too:

first3=${variable%${variable#???}}

Good call, Perderabo and Jimbo!

I love the Korn/Bourne-Again shells!

inpavan, you can read a little more about those over here: