cut through variable

hi,

can some one put more light.

i want to perform cut operation on a variable, but i am not
able to do so as the variable contain special character.

e.g var="adc|cfr\\df|{dff}|df}}"

command :

var1=`cut -c10-12 $var`

i gives error.

Thanks in advance.

$var is treated as a file in your cut command. Use echo and then pipe it to cut.

echo $var | cut -c10-12

Probably safer to double quote it, as it contains special characters.

echo "$var" | cut -c10-12

You could also use the shell's substitution facilities.

# Pluck off first ten characters
tmp1=${var#??????????}
# Now take another two
tmp2=${tmp1#??}
# Now trim everything after those two
var1=${tmp1%$tmp2}

This probably breaks if you have a too short string (but then so does the cut, albeit in a different way).

thanks for all your help

can you tell me how to cut the last two character of a variable
if the varaible is not of fix length.

right now i am performing this operation through taking size of variable
then cutting last two character.

i any short cut to it, with out taking the lenght of variable.

thanks

The variable substitution technique can be used just like I showed you above.

# Pluck off last two
tmp1=${var%??}
# Now return just the last two
var1=${var#$tmp1}

If the variable var contains abcdef then tmp1 will contain abcd, and in the final step, we trim off the value of tmp1 from the beginning of var, leaving ef

(Unclear whether you mean "take away" or "extract" the last two, but, well, this demonstrates both.)

thanks for all your help

it worked fine