简体   繁体   English

计算文件中的指定单词

[英]Count specified words in file

I want to make script, that finds how many words, that I chose, are in my chosen file. 我要创建脚本,该脚本查找我选择的文件中有多少个单词。

Here is my script: 这是我的脚本:

#!/bin/bash
echo "Iveskite reiksme kurios kurios kurios ieskosime faile"
read reiksme
echo "Nurodykite faila kuriame ieskosime reiksmes"
read failas
kiek=$(awk '/$reiksme/' $failas | wc -l)
echo $kiek > kiek.txt

if $failas contains lines like: 如果$ failas包含以下行:

$reiksme
$reiksme
$reiksme

then it's ok, but if $failas contains lines like: 没关系,但是如果$failas包含以下行:

$reiksme $reiksme
random word $reiksme $reiksme
random random $reiksme

Then my script fails to count how many words. 然后我的脚本无法计算有多少个单词。

awk is only splitting on lines. awk仅在行上拆分。 You could do it in a few steps, though there may well be easier ways than this: 您可以分几个步骤进行操作,尽管可能有比这更简单的方法:

kiek=$(sed -e 's/\s/\n/g' $failas | grep "\b${reiksme}\b" | wc -l)

to replace all whitespace with newline, then use grep (or your awk if you like) to find what you're looking for then count them 用换行符替换所有空格,然后使用grep(或awk,如果需要)查找要查找的内容,然后计算它们

I found the answer on my own. 我自己找到了答案。 I just changed 我刚换

kiek=$(awk '/$reiksme/' $failas | wc -l)

to

kiek=$(tr -cs 'A-Za-z' '\n' < $failas | grep -c "$reiksme")

The best way to do this with grep is to use the -o option as described in this post . 与要做到这一点,最好的办法grep是使用-o在描述选项这个职位 Putting it together for you: 为您整理:

kiek=$(grep -o "${reiksme}" | wc -l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM