7.
Develop a shell script that performs the following string handling operations
i) Calculate the length of the string
ii) locate a position of a character in a string
iii) extract first three characters from string.
iv) extract last three characters from string.
#!\bin\sh
echo "String Operations:"
echo “1) Calculate the length of the string \n 2) locate a position
of a character in a string \n 3) extract first three characters from
string. \n 4) extract last three characters from string.”
echo “Enter the string”
read str
echo “Enter your option”
read opt
case $opt in
'1') if [ -z "$str" ]
then
echo "null string"
else
z=`expr "$str" : '.*'`
echo "string length is $z"
fi;;
‘2’) echo “Enter the character to be searched:”
read ch
z=`expr “$str” : ‘[^‘$ch’]* ‘$ch’ ’`
echo “Character is present at $z position” ;;
‘3’) echo "first 3 characters"
z=`expr "$str" : '\(...\).*'`
echo "$z"
‘4’) echo "last 3 characters"
x=`expr "$str" : '.*\(...\)'`
echo "$x" ;;
*) echo “Invalid Choice”;;
esac
8. Shell script that accepts path names and creates all the components in that path names as
directories. For ex, if the script name is mpe, then the command mpe a/b/c/d should create directories
a, a/b, a/b/c, and a/b/c/d.
#!/bin/sh
if [ $# -ne 1 ]
then
echo " no arguments "
exit
fi
curdir=`pwd`
for dir in `echo $1 | tr '/' ' ' `
do
if [ -d $dir ]
then
echo "$dir exists under `pwd`"
cd $dir
else
mkdir $dir
echo "$dir created under `pwd`"
cd $dir
fi
done
cd $curdir
output:
$chmod +x [Link]
$sh [Link] a/b/c/d
a exists in /home/student
b exists in /home/student/a
c exists in /home/student/a/b
d exists in /home/student/a/b/c