0

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:

$reiksme
$reiksme
$reiksme

then it's ok, but if $failas contains lines like:

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

Then my script fails to count how many words.

DNA
  • 42,007
  • 12
  • 107
  • 146
demboz11
  • 917
  • 2
  • 9
  • 15

3 Answers3

1

awk is only splitting on lines. 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

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
0

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")
demboz11
  • 917
  • 2
  • 9
  • 15
0

The best way to do this with grep is to use the -o option as described in this post. Putting it together for you:

kiek=$(grep -o "${reiksme}" | wc -l)
Community
  • 1
  • 1
user1978011
  • 3,419
  • 25
  • 38