For the file file1.txt
which contains
Apple fruit Apple tree
Tree AApple AApklle Apple apple
TREE
Apple
I want to find number of occurrences of the word Apple
. Output should be 4
.
My script.sh file contains
#!/bin/bash
FILE="$1"
TOFIND="$2"
if [ -f "$FILE" ];
then
grep -o '\<"$TOFIND"\>' "$FILE" | wc -l
fi
When I try using
bash script.sh file1.txt Apple
The output shows 0
. Please help solve this problem.
One in awk:
Explained:
RS="( |\n)+"
is tested to work on gawk, mawk and Busybox awk, it failed to work on Debian's original-awk.RS="[[:space:]]+"
tested to work on gawk only.You can change the grep line to:
or just:
Then it will work. It's because the quotes, your double quotes was quoted inside single quotes, so they are not expanded.
With GNU awk for multi-char RS:
or with a shell variable: