对于包含的文件file1.txt
Apple fruit Apple tree
Tree AApple AApklle Apple apple
TREE
Apple
我想找到Apple
这个词的出现次数。输出应该是4
。
我的script.sh文件包含
#!/bin/bash
FILE="$1"
TOFIND="$2"
if [ -f "$FILE" ];
then
grep -o '\<"$TOFIND"\>' "$FILE" | wc -l
fi
当我尝试使用时
bash script.sh file1.txt Apple
输出显示0
。请帮忙解决这个问题。
您可以将grep行更改为:
grep -o '\<'"$TOFIND"'\>' "$FILE" | wc -l
要不就:
grep -o "\<$TOFIND\>" "$FILE" | wc -l
然后它会工作。这是因为引号,你的双引号是在单引号内引用的,因此它们不会被展开。
使用GNU awk进行多字符RS:
$ awk -v RS='\\<Apple\\>' 'END{print (NR ? NR-1 : 0)}' file
4
或者使用shell变量:
$ tofind='Apple'
$ awk -v RS='\\<'"$tofind"'\\>' 'END{print (NR ? NR-1 : 0)}' file
4
一个在awk:
$ awk -v w="Apple" 'BEGIN{RS="( |\n)+"}{c+=($1==w)}END{print c}' file
4
解释:
$ awk -v w="Apple" ' # search word as parameter
BEGIN {
RS="( |\n)+" # set record separator to separate words
# RS="[[:space:]]+" # where available
}{
c+=($1==w) # count searched words
}
END { # in the end
print c+0 # output count
}' file
RS="( |\n)+"
经过测试可以使用gawk,mawk和Busybox awk,它无法在Debian的原始awk上运行。 RS="[[:space:]]+"
只测试过gawk。