linux - Count occurrences with grep -
grep -o "$var" file | wc -l
it works when replace "$var" text string, not variable.
i have checked the "$var" string.
grep -o "$var" file | wc -l
it works when replace "$var" text string, not variable.
i have checked the "$var" string.
new:
hi, here code. list.txt contain multi-line word list, each line contains 1 word. source.txt 1 line file consist multiple characters without spaces.
#!/bin/bash in $(seq 1 100) word=$(sed "$i"'q;d' list.txt) #remove new line character word=${word//$'\r\n'/} grep -o "$word" source.txt | wc -l >>output done
example list.txt:
aa bb cc
example source.txt:
aaccddffzzaabbhh
what show should work expected. how fail?
in case, improve way count occurrences of each of list of words in anoter file be:
class="lang-sh prettyprint-override">#!/usr/bin/env bash while read word grep -oc "$word" source.txt >> output done < <(sed 's/\r//' list.txt)
here, using while
loop read file after removing windows style line endings. then, utilize grep's -c
alternative count occurrences. when run on illustration files, produces:
$ cat output 1 1 1
to count multiple occurrences in single line, seek this:
while read word export word; perl -lne '@c=/$env{"word"}/g; $f=scalar @c; print $f if $f>0' source.txt done < list.txt
linux grep
No comments:
Post a Comment