Use Grep to Find the Words That Have Two 'S' Separated by a Space

Use grep to find the words that have two 's' separated by a space

grep "s s"
grep "s.*s"
grep -E "^[^s]*s[^s]*s[^s]*$"

How to grep for two words existing on the same line?

Why do you pass -c? That will just show the number of matches. Similarly, there is no reason to use -r. I suggest you read man grep.

To grep for 2 words existing on the same line, simply do:

grep "word1" FILE | grep "word2"

grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.

If you just want a count of how many lines had the 2 words on the same line, do:

grep "word1" FILE | grep -c "word2"

Also, to address your question why does it get stuck : in grep -c "word1", you did not specify a file. Therefore, grep expects input from stdin, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.

Grep a whole whitespace-separated word in bash

You can use

grep -E "(^|[[:blank:]])$var($|[[:blank:]])"

Or, assuming it is a GNU grep (as suggested by Glenn Jackman):

grep -P '(?<!\S)\Q'"$var"'\E(?!\S)'

Choose the second one in case your $var contains a literal text to search for and $var can hold values containing special regex metacharacters like (, ), [, {, +, ^, etc., see What special characters must be escaped in regular expressions?
See an online demo:

s='hi helo tmp#100000 bye
100000 hi bye
hi 100000 bye'
var=100000
grep -E "(^|[[:blank:]])$var($|[[:blank:]])" <<< "$s"
# => 100000 hi bye
# hi 100000 bye

Here,

  • -E enables the POSIX ERE syntax, -P enables a PCRE syntax
  • (^|[[:blank:]]) - matches either start of input or a horizontal whitespace
  • (?<!\S)\Q - (?<!\S) checks if the char immediately on the left is a whitespace or start of string and \Q starts quoting the pattern, the $var will be parsed as a literal text
  • $var - the var contents
  • ($|[[:blank:]]) - matches either end of input or a horizontal whitespace.
  • \E(?!\S) - \E stops quoting and (?!\S) requires either a whitespace or end of string immediately on the right.

Regex for line containing one or more spaces or dashes

Something like that should work:

grep -E -- ' |\-' file.txt

Explanation:

  • -E: to interpret patterns as extended regular expressions
  • --: to signify the end of command options
  • ' |\-': the line contains either a space or a dash

Match two strings in one line with grep

You can use

grep 'string1' filename | grep 'string2'

Or

grep 'string1.*string2\|string2.*string1' filename


Related Topics



Leave a reply



Submit