In: Computer Science
Simple shell scripting
Write a Bash shell script called strcount.sh that counts the number of occurances of a given string within a file. The scripts takes two arguments: the name of the file to check and the string to count occurances of. If the file is not found (or not readable), the script should print the error message Cannot access file and exit with code -1. Otherwise, the script should print the number of occurances of the given string and exit with code 0. If the user fails to specify two arguments, the script should print the error message Usage: strcount.sh <file> <string> and exit with code -1.
Thus, if I have the following file penguins.txt:
Galapagos penguin Erect-crested penguin Subantarctic gentoo penguin Royal penguin Humboldt penguin Eastern rockhopper penguin Fiordland penguin Allied king penguin Ellsworth's gentoo penguin White-flippered penguin Cook Strait little penguin Chatham Island little penguin
Then the output should be the following:
ekrell@ekrell-desktop:~$ ./strcount.sh penguins.txt little 2
Or if the file does not exist:
ekrell@ekrell-desktop:~$ ./strcount.sh badfile.txt little Cannot access file
Or if the user fails to specify two arguments:
ekrell@ekrell-desktop:~$ ./strcount.sh Usage: strcount.sh <file> <string>
Write your script here
<- ... -> <- ... -> <- ... -> <- Add as many lines as you need ->
Credit
Material adopted from http://faculty.smu.edu/hdeshon/
check out the solution and do COMMENT if any queries.
-------------------------------------------------------------------------------------
#!/bin/bash
# check for 2 arguments along with strcount.sh
# if there no arguments then print appropriate message
if [ "$#" -ne 2 ]; then
echo "Usage : strcount.sh <file> <string>"
exit -1
else
# if arguments are present then read them in variables
filename=$1
str=$2
# check if file exists
if [ ! -f "$filename" ]; then
echo "Cannot access file"
exit -1
else
# grep - searches for the given string in given file
# -wc : word count
count=$(grep -wc "$str" "$filename")
# print the count
echo "$count"
exit 0
fi
fi
# program ends
---------------------------------------------------
---------------------------------------------
OUTPUT ::
------------------------------------
contents of penguins.txt