Linux Lab
Linux Lab
$ vi grep.sh
echo "Enter the pattern to be searched: "
read pattern
echo "Enter the file to be used: "
read filename
echo "Searching for $pattern from file $filename"
echo "The selected records are: "
grep "$pattern" $filename
echo "The no.of lines contains the word( $pattern ) :"
grep -c "$pattern" $filename
2 Write a shell script that takes a command –line argument and reports on whether it is
directory, a file, or something else.
Solution:
echo " enter file"
readstr
if test -f $str
then echo "file exists n it is an ordinary file"
elif test -d $str
then echo "directory file"
else
echo "not exists"
fi
if test -c $str
then echo "character device files"
fi
3.Write a shell script that accepts one or more file name as arguments and converts all of
them to uppercase, provided they exist in the current directory.
# get filename
echo -n "Enter File Name : "
readfileName
# make sure file exits for reading
if [ ! -f $fileName ]
then
echo "Filename $fileName does not exists"
exit 1
else
# convert uppercase to lowercase using tr command
tr '[a-z]' '[A-Z]' < $fileName
fi
4) Write a shell script to perform the following string operations:
i) To extract a sub-string from a given string.
ii) To find the length of a given string
Solution:
i) Extract a Substring from a given String
Bash provides a way to extract a substring from a string.
${string:position}
${string:position:length}
Extract substring of length $LEN from $STRING starting after position $POS. Note that first
position is 0.
STRING="this is a string"
POS=1
LEN=3
echo${STRING:$POS:$LEN}# his
echo ${#STRING} # 16 # 1234567890123456
STRING="this is a string"
echo${#STRING}# 16
5)Write a shell script that deletes all lines containing a specified word in one or more files
supplied as arguments to it.
## for this program we have to create one or more files (optional),
## I am creating two files names are del ,dell.
Solution:
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(intargc, char *argv[])
{
int fd;
struct stat X;
fd=open("abc.txt",O_RDONLY);
if((fstat(fd,&X) <0)
{
printf("file not found")
}
else printf("size %ld inode %ld ",X.st_size,X.st_ino)
}
12)Use of fork system call
13) write 10 basic commands in Linux with syntax
14)Read content of file and print on monitor using read/write system call
15) Shell script to check no is prime or not
16)shell script to check armstrong number