Sie sind auf Seite 1von 19

1.

Write a shell script that accepts a file name, starting and ending line numbers as arguments
and displays all the lines between the given line numbers.

bash-3.2$ vi lp1.sh
echo "enter the filename"

read fname

echo "enter the starting line number"

read s

a=`expr $s + 1`

echo "enter the ending line number"

read n

b=`expr $n - 1`

sed -n $a,$b\p $fname | cat > newline

cat newline

output:

bash-3.2$ sh lp1.sh

enter the filename

sales.dat

enter the starting line number

enter the ending line number

1 computers 9161

1 textbooks 21312

2 clothing 3252
2. 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.
bash-3.2$ vi del
unix is os
dos is also os
here using unix
unix is powerful os
~
bash-3.2$ vi dell
windowsnt is also os
there are some difference between unix and windowsnt
but unix is great among all os
## after creation two files now we have to write sed script file name is del.sed using vi editor.
bash-3.2$ vi del.sed
{
/os/d
}
output:
bash-3.2$ sed -f del.sed del dell
here using unix

there are some difference between unix and windowsnt


## after creation two files now we have to write sed script file name is del.sed

3. Write a shell script that displays a list of all the files in the current directory to which the user
hasread, write and execute permissions.
bash-3.2$ vi lp3.sh

echo "enter the directory name"


read dir
if [ -d $dir ]
then
cd $dir
for line in *
do
if [ -f $line ]
then
if [ -r $line -a -w $line -a -x $line ]
then
echo "$line has all permissions"
else
echo "$line not having all permissions"
fi
fi
done
fi
output:

bash-3.2$ cd cse
bash-3.2$ ls
chap1 chap2 f file1 file2
bash-3.2$ chmod 777 file1
bash-3.2$ cd ..
bash-3.2$ sh lp3.sh
enter the directory name
cse
chap1 not having all permissions
chap2 not having all permissions
f not having all permissions
file1 has all permissions
file2 not having all permissions

4. Write a shell script that receives any number of file names as arguments checks if every
argument supplied is a file or a directory and reports accordingly. Whenever the argument is a
file, the number of lines on it is also reported.
bash-3.2$ vi lp4.shl

for x in $*
do
if [ -f $x ]
then
echo " $x is a file "
echo " no of lines in the file are "
wc -l $x
elif [ -d $x ]
then
echo " $x is a directory "
else
echo " enter valid filename or directory name "
fi
done
output:

bash-3.2$ sh lp4.sh colleges cse for.sh while.sh


colleges is a file
no of lines in the file are
0 colleges
cse is a directory
for.sh is a file
no of lines in the file are
12 for.sh
while.sh is a file
no of lines in the file are
6 while.sh

5. Write a shell script that accepts a list of file names as its arguments, counts and reports the
occurrence of each word that is present in the first argument file on other argument files.
bash-3.2$ vi lp5.sh

if [ $# -ne 2 ]
then
echo "Error : Invalid number of arguments."
exit
fi
str=`cat $1 | tr '\n' ' '`
for a in $str
do
echo "Word = $a, Count = `grep -c "$a" $2`"
done

output:

bash-3.2$ cat>test
hello adams
bash-3.2$ cat>test1
hello adams
hello adams
hello
hai r u
hello
bash-3.2$ sh lp5.sh test test1
Word = hello, Count = 4
Word = adams, Count = 2

6. Write a shell script to list all of the directory files in a directory.


bash-3.2$ vi lp6.sh

echo "enter directory name"


read dir
if [ -d $dir ]
then
echo "list of files in the directory"
ls $dir
else
echo "enter proper directory name"
fi
output:

bash-3.2$ sh lp6.sh
enter directory name
cse
list of files in the directory
chap1 chap2 f file1 file2 lp2.sh

7. Write a shell script to find factorial of a given integer.


bash-3.2$ vi fact.sh

echo enter a number


read n
num=$n
fact=1
while [ $n -gt 0 ]
do
fact=`expr $fact \* $n`
n=`expr $n - 1`
done
echo "factorial of $num is $fact"
output:

bash-3.2$ sh fact.sh
enter a number
5
factorial of 5 is 120

8. Write an awk script to count the number of lines in a file that do not contain vowels.
9. Write an awk script to find the number of characters, words and lines in a file.
bash-3.2$ vi count.awk

BEGIN{print "record.\t characters \t words"}


#BODY section
{
len=length($0)
total_len+=len
print(NR,":\t",len,":\t",NF,$0)
words+=NF
}
END{
print("\n total")
print("characters :\t" total_len)
print(“words :\t”words)
print("lines :\t" NR)
}
output:
-bash-3.2$ cat ex
this is an example of awk
counting vowels
not containing in lines

bash-3.2$ awk –f count.awk ex


record. characters words
1: 25 : 6 this is an example of awk
2: 15 : 2 counting vowels
3: 23 : 4 not containing in lines

total
characters : 63
words: 12
lines : 3

8. Write an awk script to count the number of lines in a file that do not contain vowels.

-bash-3.2$ vi lp8.sh

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if 1 argument is passed


if [ $# -ne 1 ]
then
echo "Usage: ./lp8.sh <file_name>"
exit 1
fi

awk ' BEGIN { line_count = 0 } # Initialize line_coun


!/[aeiou]/ { line_count++; print } # Count the lines without aeiouo
END { printf "Number of lines which do not contain vowels “aeiou” = %d\n",
line_count } # Display the statistics
' $1
#awk '$0 !~ /[aeiou]/ { print }' $1

Output

-bash-3.2$ cat shellex


this is an example of awk program.
aaaaaaaaaaaaa
bbbbbbbbbbbbbb
ccccccccccccc

-bash-3.2$ sh lp8.sh shellex


bbbbbbbbbbbbbb
ccccccccccccc
Number of lines which do not contain vowels = 2

10. Write a c program that makes a copy of a file using standard I/O and system calls

bash-3.2$ vi lp10.c

#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd1, fd2;
char buffer[100];
long int n1;
if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2=open(argv[2],O_CREAT|O_WRONLY|
O_TRUNC,
0700)) == -1)){
perror("file problem ");
exit(1);
}
while((n1=read(fd1, buffer, 100)) > 0)
if(write(fd2, buffer, n1) != n1){
perror("writing problem ");
exit(3);
}
}

output:
-bash-3.2$ cat del
unix is os
dos is also os
here using unix
unix is powerful os

-bash-3.2$ cc lp10.c

-bash-3.2$ ./a.out del exdel

-bash-3.2$ cat exdel


unix is os
dos is also os
here using unix
unix is powerful os

11. Implement in C the following Unix commands and System calls.

a. Cat
b. ls
c. mv.

a) Implement in C the ‘cat’ Unix command using system calls


bash-3.2$ vi catex.c
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[3] )
{
int fd,i;
char buf[100];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-1)
{
printf("file open error");
}
else
{
while(i=read(fd,buf,1)>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}
output:
-bash-3.2$ cat col1
akits
anubose
srr
adams
vijaya
-bash-3.2$ cc ex2.c
-bash-3.2$ ./a.out col1
Welcome to ATRI
akits
anubose
srr
adams
vijaya

b) Implement in C the Unix command ‘mv’ using system calls

-bash-3.2$ vi lp2.c
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s \n",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}
Output

-bash-3.2$ cat random


this is a random file
-bash-3.2$ cat sample
cat: sample: No such file or directory

-bash-3.2$ cc lp2.c
-bash-3.2$ ./a.out random sample
file1=random file2=sample
-bash-3.2$ cat sample
this is a random file
-bash-3.2$ cat random
cat: random: No such file or directory

c) Implement in C the ‘ls’ Unix command using system calls

-bash-3.2$ vi lp3.c

#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
extern int alphasort();
char pathname[MAXPATHLEN];
main() {
int count,i;
struct dirent **files;
int file_select();
if (getwd(pathname) == NULL )
{ printf("Error getting pathn");
exit(0);
}
printf("Current Working Directory = %sn",pathname);
count = scandir(pathname, &files, file_select, alphasort);
if (count <= 0)
{ printf("No files in this directoryn");
exit(0);
}
printf("Number of files = %dn",count);
for (i=1;i<count+1;++i)
printf("%s \n",files[i-1]->d_name);
}
int file_select(struct direct *entry)
{
if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0))
return (FALSE);
else
return (TRUE); }

Output
-bash-3.2$ cc lp3.c
-bash-3.2$ ./a.out

12. Write a program that takes one or more file/directory names as command line input and
reports the following information on the file.
A. File type. B. Number of links.
C. Time of last access. D. Read, Write and Execute permissions.

-bash-3.2$ vi lp12.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<time.h>

#define ERR (-1)


#define TRUE 1
#define FALSE 0

int main();

int main(argc, argv)


int argc;
char *argv[];

{
int isdevice = FALSE;
struct stat stat_buf;

if (argc != 2)
{
printf("Usage: %s filename\n", argv[0]);
exit (1);
}
if ( stat( argv[1], &stat_buf) == ERR)
{
perror("stat");
exit (1);
}
printf("\nFile: %s status:\n\n",argv[1]);
if ((stat_buf.st_mode & S_IFMT) == S_IFDIR)
printf("Directory\n");
else if ((stat_buf.st_mode & S_IFMT) == S_IFBLK)
{
printf("Block special file\n");
isdevice = TRUE;
}
else if ((stat_buf.st_mode & S_IFMT) == S_IFCHR)
{
printf("Character special file\n");
isdevice = TRUE;
}
else if ((stat_buf.st_mode & S_IFMT) == S_IFREG)
printf("Ordinary file\n");
else if ((stat_buf.st_mode & S_IFMT) == S_IFIFO)
printf("FIFO\n");
if (isdevice)
printf("Device number:%d, %d\n", (stat_buf.st_rdev > 8) & 0377,
stat_buf.st_rdev & 0377);

printf("I-node: %d; Links: %d; Size: %ld\n", stat_buf.st_ino,


stat_buf.st_nlink, stat_buf.st_size);
printf("file last accessed:%s\n",ctime(&stat_buf.st_atime));
if ((stat_buf.st_mode & S_ISUID) == S_ISUID)
printf("Set-user-ID\n");
if ((stat_buf.st_mode & S_ISGID) == S_ISGID)
printf("Set-group-ID\n");
if ((stat_buf.st_mode & S_ISVTX) == S_ISVTX)
printf("Sticky-bit set -- save swapped text after use\n");
printf("Permissions: %o\n", stat_buf.st_mode & 0777);

exit (0);
}

Output
-bash-3.2$ cc lp12.c
-bash-3.2$ ./a.out del

File: del status:

Ordinary file
I-node: 23861966; Links: 1; Size: 64
file last accessed:Thu Aug 28 14:52:44 2014

Permissions: 644
13. Write a C program that redirects a standard output to a file. Ex: ls >f1.

-bash-3.2$ vi lp13.c

/* freopen example: redirecting stdout */


#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}

Output
-bash-3.2$ cc lp13.c
-bash-3.2$ ./a.out
-bash-3.2$ cat myfile.txt
This sentence is redirected to a file.

14. Write a C program to list for every file in a directory, its inode number and file name.
-bash-3.2$ vi lp14.c

#include <string.h> /* String functions (strcat) */


#include <dirent.h> /* DIR, dirent, etc. */
#include <stdio.h> /* printf, etc. */
#include <stdlib.h> /* exit, etc. */

/* Define all the error messages */


char * error_msg[] = {
"\nUsage: ./14lsi\n\n",
"\nCould not retrieve the current working directory\n\n",
"\nCould not open the current working directory\n\n",
"\nCould not scan the directory\n\n"
};

void print_error(int msg_num, int exit_code);

int main(int argc, char * argv[])


{
int i; /* A counter */
DIR * dir_to_read; /* Handle to directory to be read */
struct dirent ** dir_entry;/* Array to hold individual entries of dir sorted */
int num_entries; /* Number of entries in the directory */
char * cur_work_dir = NULL;/* String to hold current working directory name */
char success_msg[] = "\nCommand executed successfully\n\n";

/* Check if correct number of arguments are supplied */


if ( argc > 1 ) print_error(0,2);

/* Get the current working directory */


if ( (cur_work_dir = (char *)get_current_dir_name()) == NULL ) print_error(1,3);

/* Open the current working directory */


if ( (dir_to_read = opendir(cur_work_dir)) == NULL ) print_error(2,4);

/* Get the current directory alphabetically sorted */


if ( (num_entries = scandir(cur_work_dir, &dir_entry, 0, alphasort)) < 0 )
print_error(3,5);
else
{
/* Loop through sorted current working directory and display each file
name till all the entries are exhausted */
for ( i = 0; i < num_entries; i++ )
{
/* Display the directory entry */
printf("%d %s\n",(int)dir_entry[i]->d_ino,dir_entry[i]->d_name);
}
}

printf("%s", success_msg);

return 1;
}
void print_error(int error_index, int exit_code)
{
fprintf(stderr, "%s", error_msg[error_index]);

exit(exit_code);

Output

-bash-3.2$ cc lp14.c
-bash-3.2$ ./a.out

15. Write a C program to emulate the UNIX ls –l command

-bash-3.2$ vi lp14.c

#include <string.h> /* String functions (strcat) */


#include <dirent.h> /* DIR, dirent, etc. */
#include <sys/stat.h> /* struct stat */
#include <sys/types.h> /* S_IFMT */
#include <stdio.h> /* sprintf, etc. */
#include <stdlib.h> /* exit, etc. */
#include <time.h> /* strftime, ctime */
#include <pwd.h> /* struc passwd (to retrieve user name) */
#include <grp.h> /* struc group (to retrieve group name) */
#define MAX_MSG_LEN 200 /* Maximum length of temporary string */

/* Define all the error messages */


char * error_msg[] = {
"\nUsage: ./13lsl\n\n",
"\nCould not retrieve the current working directory\n\n",
"\nCould not open the current working directory\n\n",
"\nError doing 'stat' on file\n\n",
"\nCould not scan the directory\n\n"
};
void print_error(int msg_num, int exit_code);
int main(int argc, char * argv[])
{
int i; /* A counter */
char msg[MAX_MSG_LEN] = ""; /* A temporary string */
struct passwd * passwd_details; /* Structure to retrieve user name */
struct group * group_details; /* Structure to retrieve group name */
struct tm * tmptime; /* To store file modification time in 'tm' struc */
char time_str[MAX_MSG_LEN]; /* String representation of time */
char mode_str[11]; /* String to hold file type and permissions */
mode_t file_perm; /* File permissions */
DIR * dir_to_read; /* Handle to directory to be read */
struct dirent ** dir_entry; /* Array to hold individual entries of dir sorted */
int num_entries; /* Number of entries in the directory */
struct stat file_details; /* Detailed file info */
char * cur_work_dir = NULL; /* String to hold current working directory name */
char success_msg[] = "\nCommand executed successfully\n\n";

/* Check if correct number of arguments are supplied */


if ( argc > 1 ) print_error(0,2);

/* Get the current working directory */


if ( (cur_work_dir = (char *)get_current_dir_name()) == NULL )
print_error(1,3);

/* Open the current working directory */


if ( (dir_to_read = opendir(cur_work_dir)) == NULL )
print_error(2,4);

/* Get the current directory alphabetically sorted */


if ( (num_entries = scandir(cur_work_dir, &dir_entry, 0, alphasort)) < 0 )
print_error(4,6);
else
{
/* Loop through sorted current working directory and display each file
name till all the entries are exhausted */
for ( i = 0; i < num_entries; i++ )
{
/* Retrieve the file details */
if (lstat(dir_entry[i]->d_name,&file_details) < 0)
print_error(3,5);
/* Prepare the mode string */

/* Get the file type */


if ( S_ISREG(file_details.st_mode) ) strcpy(mode_str,"-");
else if ( S_ISDIR(file_details.st_mode) ) strcpy(mode_str,"d");
else if ( S_ISLNK(file_details.st_mode) ) strcpy(mode_str,"l");
else strcpy(mode_str,"?");

/* Get the octal file permissions */


file_perm = file_details.st_mode & ~S_IFMT;
if ( file_perm & S_IRUSR )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWUSR )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXUSR )
strcat(mode_str,"x");
else
strcat(mode_str,"-");
if ( file_perm & S_IRGRP )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWGRP )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXGRP )
strcat(mode_str,"x");
else
strcat(mode_str,"-");
if ( file_perm & S_IROTH )
strcat(mode_str,"r");
else
strcat(mode_str,"-");
if ( file_perm & S_IWOTH )
strcat(mode_str,"w");
else
strcat(mode_str,"-");
if ( file_perm & S_IXOTH )
strcat(mode_str,"x");
else
strcat(mode_str,"-");

/* Initialize the temporary string 'msg' */


strcpy(msg,"");

/* Get the file permissions in temporary string 'msg' */


sprintf(msg,"%s%s ",msg,mode_str);

/* Get the number of links */


sprintf(msg,"%s%d ",msg,(int)file_details.st_nlink);

/* Get the User name */


passwd_details = getpwuid(file_details.st_uid);
sprintf(msg,"%s%s ",msg,passwd_details->pw_name);

/* Get the Group name */


group_details = getgrgid(file_details.st_gid);
sprintf(msg,"%s%s ",msg,group_details->gr_name);

/* Get the size of the file */


sprintf(msg,"%s%6d ",msg,(int)file_details.st_size);

/* Get the last modification time of the file */


tmptime = localtime(&file_details.st_mtime);
strftime(time_str, sizeof(time_str), "%F %R", tmptime);
sprintf(msg,"%s%s ",msg,time_str);

/* Get the file name */


sprintf(msg,"%s%s\n",msg,dir_entry[i]->d_name);

/* Display file details */


printf("%s",msg);
} /* end for */
} /* end else */
printf("%s", success_msg);
return 1;
}

void print_error(int error_index, int exit_code)


{
fprintf(stderr, "%s", error_msg[error_index]);
exit(exit_code);
}
Output
-bash-3.2$ cc lp15.c
-bash-3.2$ ./a.out

Das könnte Ihnen auch gefallen