0

I'm using

if[ "$wordCount" -gt 10 ]

To check if there are more than 10 words in the line, but how can I also check if a specific string, say "Brown Cow" is also within the line?

So the conditional should only work if the line has a wordCount of over 10 and contains the string "Brown Cow" within the $line string. Is there a way to do that within Linux/Bash? Or will I need a multi-line or different conditional like case to do it?

  • Does this answer your question? [Bash if statement with multiple conditions throws an error](https://stackoverflow.com/questions/16203088/bash-if-statement-with-multiple-conditions-throws-an-error) or [Two conditions in a bash if statement](https://stackoverflow.com/q/11370211/7366100) – markp-fuso Sep 30 '20 at 01:58
  • Also, for the substring test: [How to check if a string contains a substring in Bash](https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash). – Gordon Davisson Sep 30 '20 at 03:18
  • where are you setting a variable name `$line`? Please update your Q to show all relevant code AND input (data/files/strings?) and the required output from that same sample input. Otherwise we'll be playing 20 questions with you in comments. Good luck. – shellter Sep 30 '20 at 03:26

2 Answers2

0

Using grep and then piping to the while loop, I was able to get it to work by just only running the lines with the specified string into the loop in the first place and using the same conditional if statement with:

grep -n "Brown Cow" fileName | while read line;
do 
      lineNumber=$(echo $line | cut -d: -f1)
      lineText=${line#*;}
      wordCount=`echo $line | wc -w`
      if[ "$wordCount" -gt 10 ]
          Commands
done

Should I update my original question to show more code or is this a sufficient answer for anyone who runs into a similar issue in the future?

0

You can use a regular expression or glob pattern in a [[ expression. Since the string you're looking for has spaces, it needs to be in a variable to compensate for parser restrictions:

phrase="Brown Cow"
if [[ $wordCount -gt 10 && $line =~ $phrase ]]; then
    # Success
else
    # Failure
fi

or

# Note the *'s for a wildcard pattern match
phrase="*Brown Cow*"
if [[ $wordCount -gt 10 && $line = $phrase ]]; then
    # Success
else
    # Failure
fi

Shawn
  • 47,241
  • 3
  • 26
  • 60