Pages

Practice Scripts

Try out the following scripts


Lets try writing different scripts using what we have learnt till now.

Create a file named are "file1" with the following contents

"The command line is very powerful and fast.Once you get used to the using the
commands in commmand line, a lot of things become very easy to do.
The graphical user interface is slow as well as very restrivtive in its options.
 Learn the commmand line it will help in automating a number of tasks.The
command line also requires lesser amount of memory resource as compared to  
the GUI"


Questions:
1. Write a script to that will ask the user for a string and count the number of lines that have the string in it.

2. Write a script to that will ask the user for a string and count the number of times the string appears in file1.

3. Write a script that will ask the user for a string and output all the lines that do not have the string in them.

4. write a script that will take a number as the input and output only that many lines from the file1, from the top.



Solutions:

1.
#!/bin/bash
# A script to count the number of lines that have a certain word.

read string
echo "Searching for $string"
count=$(grep -c  $string file1)
echo "There are $count lines with the word $string"

2.
#!/bin/bash
# A script to count the number of times a string appears.

read string
echo "Searching for $string"
count=$(grep -o $string | grep -c)
echo "There are $count occurences of $string in file1"

3.
#!/bin/bash
# A script to output the lines that do not contain a certain string

echo "Enter the string"
read string

grep -v $string file1

4.
 #!/bin/bash
# A script that will output specific number of lines of the file1

echo "Enter the number of lines needed in the ouput"
read number

head $number file1

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete