grep-o“$var”文件wc-l
当我用文本字符串替换“$var”而不是变量时,它起作用。
我已经检查过“$var”是一个字符串。
grep-o“$var”文件wc-l
当我用文本字符串替换“$var”而不是变量时,它起作用。
我已经检查过“$var”是一个字符串。
新
嗨,这是密码。
list.txt包含多行单词列表,每行包含一个单词。
source.txt是一个单行文件,由多个字符组成,没有空格。
#!/bin/bash
for i in $(seq 1 100)
do
word=$(sed "$i"'q;d' list.txt)
#remove the new line character
word=${word//$'\r\n'/}
grep -o "$word" source.txt | wc -l >>output
done
示例list.txt:
aa
bb
cc
示例source.txt:
aaccddffzzaabbhh
最佳答案
你所展示的应该是预期的。怎么会失败?
无论如何,计算另一个文件中每个单词列表出现次数的更好方法是:
#!/usr/bin/env bash
while read word
do
grep -oc "$word" source.txt >> output
done < <(sed 's/\r//' list.txt)
在这里,我使用
while
循环来读取删除windows样式行结束后的文件。然后,我使用grep的-c
选项来计算出现次数。在示例文件上运行时,将生成:$ cat output
1
1
1
要计算一行中的多次出现次数,可以尝试以下操作:
while read word
do
export word;
perl -lne '@c=/$ENV{"word"}/g; $f=scalar @c; print $f if $f>0' source.txt
done < list.txt
关于linux - 用grep计数出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26189686/