Friday 17 August 2018

Grep Command in Unix Shell script

Q) How to use the grep command in unix or linux bash scripts to search for a pattern match?


You might have used the grep command to search for a string in a file on the unix command line. Here we will see how to use the grep command in a bash script.

Grep Command, Unix Shell Script, LPI Certification, LPI Tutorial and Material, LPI Guides

Consider the below file with data

> cat sample_file.txt
linux storage
unix distributed system
linux file server
debian server
fedora backup server

Let see the bash script that prints the lines which contain the word server in it. The bash script code is shown below:

>vi grep_script.sh

#!/bin/bash

WORD=server
INPUT_FILE=sample_file.txt
grep "$WORD" $INPUT_FILE

Now we will execute this script and see what the output is

> bash grep_script.sh

linux file server
debian server
fedora backup server

Grep Command, Unix Shell Script, LPI Certification, LPI Tutorial and Material, LPI Guides
Here in the script we have hardcoded the filename and the search pattern. We will see how to pass these as arguments from the command line to the script. The bash script is:

>vi grep_script_command_line.sh

#!/bin/bash

INPUT_FILE=$1
WORD=$2
grep "$WORD" $INPUT_FILE

Now run the script as shown below:

> bash grep_script_command_line.sh sample_file.txt server

Related Posts

0 comments:

Post a Comment