I want to count the number of 6-letter words that start with 'bar' and end with 'i' or 'n'.

For example, given this file:


the output should be 2 (integer), since these lines match:


My code is the following, but it seems to be wrong:

grep -c 'bar??[ni]' /path/file.txt
  • I'm learning Unix and I have to accomplish this assignment by only using -wc or -grep. – Ulysses Jan 31 '18 at 13:41
  • 1
    You seem to be confusing shell globs (where ? means "any single character") with regular expression syntax (where it's a repetition modifier). – steeldriver Jan 31 '18 at 13:42
  • @MarkPlotnick I was doing a bigger edit when yours came. I rolled yours back in the hope that the final version is clear enough. Feel free to change the post if you think it can be improved. – fedorqui Jan 31 '18 at 13:47
  • 1
    @fedorqui No problem, your edits made it even better. – Mark Plotnick Jan 31 '18 at 13:48

Use grep -o which outputs only the matched text, multiple time per line if necessary.

grep -o '\<bar[^ ][^ ][ni]\>' /path/file.txt | wc -w

The \< and \> match the beginning and end of a word. The [^ ] matches a non-space character.

  • yeah this is a good approach – Ulysses Jan 31 '18 at 13:52

Replace your question marks ? with periods . and your grep should work, as long as your input is only one word per line.

grep -c 'bar..[ni]' /path/file.txt
  • sure and why . instead of ? I thought ? was for a single char – Ulysses Jan 31 '18 at 13:53
  • The question mark character represents a single character in shell globbing syntax, not in regular-expression syntax. – user1404316 Jan 31 '18 at 14:09
awk '{ for (i=1;i<=NF;i++) if ($i ~ /^bar.*[in]/ || $i ~ /[[:space:]]bar.*[in]/) { count++ }} END { print count }' filename

The above awk solution should also work. Taking account of multiple entries on each line, awk looks from the first space delimited entry in the file on each line to the last entry (NF) if then pattern matches against regular expressions with ~ and increments a count accordingly. Two if statements are created to take account or a beginning of line (^) and bar as well a space and bar. At the end, the count is printed to screen.

  • He has to accomplish this assignment by only using wc or grep, apparently – wurtel Jan 31 '18 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.