1 采用grep
grep 里面有个 -o 选项,这个选项我还真不知道,今天看了一篇博文,才知道有这个选项。
- -o, --only-matching
- Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
- cat test.txt
- manu is good boy, manu study linux kernel
- manu is in nanjing
- grep -o manu test.txt
- manu
- manu
- manu
- grep -o manu test.txt |wc -l
- 3
2 awk
awk 里面有个函数叫做gsub,可以理解为global substitude, 全局替换。这个函数会返回找到的个数:
- root@manu:~/code/shell # awk '{s+=gsub(/manu/,"manuscola"); print }END{print s}' test.txt
manuscola is good boy, manuscola study linux kernel
manuscola is in nanjing
3
这样的话,我们就得到了第二个方法:
- awk '{s+=gsub(/字符串/,"")}END{print s}' file
当然这个题目有很多其他的办法。掌握更多的命令的用法,做大量的练习,最终达到运用自如的程度。
参考文献:
1 The AWK Manual
2 man grep