0

H! So I am trying to run a script which looks for a string pattern.

For example, from a file I want to find 2 words, located separately

"I like toast, toast is amazing. Bread is just toast before it was toasted."

I want to invoke it from the command line using something like this:

./myscript.sh myfile.txt "toast bread"

My code so far:

text_file=$1
keyword_first=$2
keyword_second=$3
find_keyword=$(cat $text_file | grep -w "$keyword_first""$keyword_second" )
echo $find_keyword

i have tried a few different ways. Directly from the command line I can make it run using:

cat myfile.txt | grep -E 'toast|bread'

I'm trying to put the user input into variables and use the variables to grep the file

  • 3
    Note that by quoting your arguments ("toast bread") they get treated as a single argument, not as two arguments. You can always check what your script is doing in the background and how it is treating variables by starting it with `bash -x yourscript` – mashuptwice Mar 26 '22 at 11:34

2 Answers2

1

You seem to be looking simply for

grep -E "$2|$3" "$1"

What works on the command line will also work in a script, though you will need to switch to double quotes for the shell to replace variables inside the quotes.

In this case, the -E option can be replaced with multiple -e options, too.

grep -e "$2" -e "$3" "$1"
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

You can pipe to grep twice:

find_keyword=$(cat $text_file | grep -w "$keyword_first" | grep -w "$keyword_second")

Note that your search word "bread" is not found because the string contains the uppercase "Bread". If you want to find the words regardless of this, you should use the case-insensitive option -i for grep:

find_keyword=$(cat $text_file | grep -w -i "$keyword_first" | grep -w -i "$keyword_second")

In a full script:

#!/bin/bash
#
# usage: ./myscript.sh myfile.txt "toast" "bread"
text_file=$1
keyword_first=$2
keyword_second=$3
find_keyword=$(cat $text_file | grep -w -i "$keyword_first" | grep -w -i "$keyword_second")
echo $find_keyword
pcamach2
  • 443
  • 2
  • 13
  • You'll want to avoid the [useless use of `cat`](https://stackoverflow.com/questions/11710552/useless-use-of-cat). – tripleee Mar 26 '22 at 20:58
  • The OP's code looks for either of these words, whereas your code will only find lines which contain both. – tripleee Mar 26 '22 at 20:59
  • I interpreted the question as asking for a method to find a line with both words not next to each other in a string – pcamach2 Mar 26 '22 at 21:04