Home > database >  User input into variables and grep a file for pattern
User input into variables and grep a file for pattern

Time:03-27

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

CodePudding user response:

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"

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related