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.
Consider the below file with data
Let see the bash script that prints the lines which contain the word server in it. The bash script code is shown below:
Now we will execute this script and see what the output is
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:
Now run the script as shown below:
Recommended Reading:
Awk Command in Unix
Different Ways to Find Length of String in Unix Bash Script
How to Parse CSV File - Unix bash script
File Test Operations in Unix Shell Script
How to Connect to Oracle Database in Unix Shell script
If you like this article, then please share it or click on the google +1 button.
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.
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
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
Recommended Reading:
Awk Command in Unix
Different Ways to Find Length of String in Unix Bash Script
How to Parse CSV File - Unix bash script
File Test Operations in Unix Shell Script
How to Connect to Oracle Database in Unix Shell script
If you like this article, then please share it or click on the google +1 button.
Post a Comment