Powered By Blogger

Aug 6, 2024

Operating System Lab Practical-05

 

Practical-5

Title : Shell Script programming using grep, awk, sed


____________________________________________________________________


Shell Script programming using grep :

Suppose you have a directory structure like this:


/home/cse40/lab5


|-- file1.txt

|-- file2.txt

|-- lab5subdir

    |-- file3.txt


And the content of the files are:

- `file1.txt`: "Hello world"

- `file2.txt`: "This is a test"

- `file3.txt`: "Hello again"


Now, if you want to search for the word "Hello" in the `/lab5`, you can use the script as follows:

$touch grep_script.sh


#!/bin/bash

# Check if the correct number of arguments is provided

if [ "$#" -ne 2 ]; then

    echo "Usage: $0 <pattern> <directory>"

    exit 1

fi

pattern=$1

directory=$2

# Search for the pattern in the specified directory and its subdirectories

grep -r "$pattern" "$directory"


1. Save the script in a file named `grep_script.sh`.

2. Make the script executable: $chmod +x grep_script.sh

3. Run the script with the pattern "Hello" and the directory `/lab5`:

      ./grep_script.sh "Hello" /home/cse40/lab5

   

Expected Output:

/home/cse40/lab5/file1.txt:Hello world

/home/cse40/lab5/lab5subdir/file3.txt:Hello again


This output shows the lines containing the word "Hello" along with the file names where the pattern was found.


Shell Script programming using awk :

 

Awk is a scripting language used for manipulating data and generating reports. The awk command programming language requires no compiling and allows the user to use variables, numeric functions, string functions, and logical operators.


Here is a simple `awk` script example to extract and print specific columns from a file:

$touch awk_script.sh

$nano awk_script.sh


#!/bin/bash

# Check if the correct number of arguments is provided

if [ "$#" -ne 3 ]; then

    echo "Usage: $0 <column1> <column2> <file>"

    exit 1

fi

column1=$1

column2=$2

file=$3

# Use awk to print the specified columns

awk -v col1="$column1" -v col2="$column2" '{print $col1, $col2}' "$file"


Suppose you have a file `data.txt` with the following content:

1 Raj 25

2 Sunil 30

3 Vinit 22

4 Rahul 28


If you want to extract and print the first and third columns (ID and age), you can use the script as follows:


1.    Save the script as `awk_script.sh`.

2. Make the script executable: $chmod +x awk_script.sh

3. Create the `data.txt` file:

      echo -e "1 Raj 25\n2 Sunil 30\n3 Vinit 22\n4 Rahul 28" > data.txt

4. Run the script:  ./awk_script.sh 1 3 data.txt

   

Expected Output:

1 25

2 30

3 22

4 28

This output shows the first and third columns of each line from the `data.txt` file. 




Shell Script programming using sed :


SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it.

  • SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution).

  • SED command in unix supports regular expression which allows it perform complex pattern matching.



$touch awk_script.sh

$nano awk_script.sh



#!/bin/bash

# Check if the correct number of arguments is provided

if [ "$#" -ne 3 ]; then

    echo "Usage: $0 <pattern> <replacement> <file>"

    exit 1

fi

pattern=$1

replacement=$2

file=$3

# Use sed to replace the pattern with the replacement string in the specified file

sed -i "s/$pattern/$replacement/g" "$file"



Suppose you have a file `example.txt` with the following content:

Hello world

This is a test

Hello again


If you want to replace the word "Hello" with "Hi", you can use the script as follows:


1. Save the script as “sed_script.sh”.

2.Make the script executable:$ chmod +x sed_script.sh

3. Create the `example.txt` file: 

    echo -e "Hello world\nThis is a test\nHello again" > example.txt

4. Run the script:

   ./sed_script.sh "Hello" "Hi" example.txt

   

Expected Output in “example.txt”:


Hi world

This is a test

Hi again


This script replaces all occurrences of the word "Hello" with "Hi" in the `example.txt` file.



Operating System Lab Practical-04

 

Practical: 04

Title : Basic of Shell programming


Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script.

Creating a Shell Script :


Login to your Linux machine and open the terminal, navigate to the folder where you want to store the shell script.Shell scripts end with the extension “.sh”. Let’s create our first shell script. Type in  

$touch script.sh


Now, this script file is not executable by default, we have to give the executable permission to this file. Type in

$chmod +x script.sh

Now, we will add some commands to this shell script. Open this shell script with any text editor of your choice (command-line based or GUI based) and add some commands. We will use nano. Type in

$nano script.sh

Add the following commands to test this shell script

echo This is my first shell script

touch testfile

ls

echo End of my shell script


Save the changes, and run the shell script by typing in

$./script.sh


Comments in the shell script

Any line which starts with “#” in the shell script is treated as a comment and is ignored by the shell during execution, except the shebang line, which we will see later in this article. Let’s see an example. A shell script is created with the following content.

# This is a comment

echo Testing comments in shell script



Variables in Shell Script


There are two types of variables:

  • System Defined variables

  • User-Defined Variables.

System-defined variables, also called environment variables, are generally Capitalised. You can view all the current environment variables using the printenv command. User-Defined variables are set by the user, and they exist only during script execution. You can define a variable by simply typing its name and assigning a value with = sign and access a variable by adding a $ before the variable name. Variables are demonstrated in the following example script.

# Accessing an Environment Variable

echo $USER


# Creating and accessing User defined Variable

variable_name="JNEC MGMU"

echo $variable_name



Defining the Shell Script interpreter

There are many Shells available in Linux, such as The bourne shell(sh), The Korn Shell(ksh), and GNU Bourne-Again Shell(bash). Scripts written for the sh shell are called shell scripts, and they can be interpreted by both, the ksh and bash shells. ksh and Bash are improved versions of the original sh shell and they have more features than sh. Bash is generally the default shell in most of the Linux Distributions and scripts written specifically for bash shell are called bash scripts. 

You can specify which shell the script will use, even if the script is executed from another shell terminal. To do this, add “#!” on top of the script file, followed by the absolute path of the shell of choice. To specify bash as an interpreter, Add the following line on top of the shell script.


You can specify which shell the script will use, even if the script is executed from another shell terminal. To do this, add “#!” on top of the script file, followed by the absolute path of the shell of choice. To specify bash as an interpreter, Add the following line on top of the shell script.



#!/bin/bash

This line is called the shebang line.

Note: This will only work if bash is installed on your system.

Conditional statements

IF THAN :


#!/bin/sh

x=10

y=11

if [ $x -ne $y ] 

then

echo "Not equal"

fi


IF THEN ELSE: 


#!/bin/sh

x=10

y=10

if [ $x -ne $y ] 

then

echo "Not equal"

else

echo "They are equal"

fi


Loops

Using loops, you can a set of commands over and over again, until a certain condition is met. 

WHILE LOOP:


#!/bin/sh

x=2

while [ $x -lt 6 ]

do

echo $x

x=`expr $x + 1`

done


FOR LOOP  :


#!/bin/sh

for var in 2 4 5 8

do

echo $var

done



Positional Arguments

Positional arguments are the arguments or values which we pass to the shell script while executing the script. They are accessed by variables $0, $1, $2 … $9. Beyond that, they are referenced by ${10}, ${11} and so on. $# stores the no of passed arguments and $0 stores the name of the script. Let’s see an example to understand all this.

#!/bin/sh

echo "No of arguments is $#"

echo "Name of the script is $0"

echo "First argument is $1"

echo "Second argument is $2"


Storing the output of commands

You can store the output of commands inside a variable in a shell script. There are two ways to do so.

Syntax

#Syntax 1

var=$(a valid linux command)

#Syntax 2

var2=`a valid linux command`

Let’s see an example.

#!/bin/sh

b=$(pwd)

c=`pwd`

echo $b

echo $c

d=$(ls /bin | grep bash)

echo $d


Exit Codes of shell commands

Whenever a command ends and returns the control to the parent process, it returns exit codes between 0 and 255. Exit code 0 means the command was successful, and any other exit code means, the command was unsuccessful. You can view the exit code after running any command by accessing the $? variable. 


$pwd

$ echo $?

$pwds

$echo $?


You can manually set an exit code for your shell script. This can be used with conditional statements to convey if the script’s purpose was achieved or not. 

Example

#!/bin/sh

read x

if [ $x -ne 10 ]

then

echo failed

exit 1

else

echo passed

exit 0

fi






Operating Systems Practical-03

 

Practical: 03

Title: Hands on Unix / Linux command 


1. Is:

The ls command is commonly used to identify the files and directories in the working directory. This command is one of the many often-used Linux commands that you should know.

$ls

Output:


2. pwd :

The pwd command is mostly used to print the current working directory on your terminal. It is also one of the most commonly used commands.

$pwd

Output:


3. mkdir :

This mkdir command allows you to create fresh directories in the terminal itself. The default syntax is mkdir <directory name> and the new directory will be created.

$mkdir mgmu

Output:


4. cd:

The cd command is used to navigate between directories. It requires either the full path or the directory name, depending on your current working directory. If you run this command without any options, it will take you to your home folder. Keep in mind that it can only be executed by users with sudo privileges.

$pwd

$cd <directory name>

$pwd

Output:


5. rmdir:

The rmdir command is used to delete permanently an empty directory. To perform this command the user running this command must be having sudo privileges in the parent directory.

$ls

$rmdir <directory name>

$ls

Output:


6. cp:

The cp command of Linux is equivalent to copy-paste and cut-paste in Windows. 

$cp Src_file Dest_file

$gedit a.txt      ( Insert some text in file and save)

$gedit b.txt      (Leave bank and same file)

$cat a.txt         (see content of a.txt)

$cat b.txt         (no content in b.txt)

$cp a.txt b.txt   (copy of a.txt to b.txt)

$cat a.txt         (see content of a.txt)

$cat b.txt         (see content of b.txt)

Output:




Featured Post

Data Analysis

    What is data analysis and its significance?   Data analysis is the process of collecting, transforming, and organizing data to dr...

Popular Posts