I'm trying to make a bash script to search for words in multiple text files; there are 4 parameters but the script works only if I search for all of these, not if I search only for one or more (eg word3 and word4). Word2 is a number with variable length that I don't know and I don't care about; I tried so to add a wildcard * but it gives me an error.
How can I modify the script so that I can search for one, two more or all parameters, given that word2 is not known?
#!/bin/bash
read -p "word3: " word3
read -p "word4: " word4
read -p "word1: " word1
read -p "word2: " word2
printf "Searching for ${word1}:${word2}:${word3}:${word4} $(find path/to/file -name '*.txt')"
grep -i -w "${word1}:${word2}:${word3}:${word4}" $(find path/to/file -name '*.txt') | cut -d":" -f2-
Output example is:
word1:numbervariablelenght:word3:word4
EDIT1:
*sample input
bash script.sh
word3: wordThree
word4: wordFour
word1: wordOne
word2: don't know
Searching for word1:word2:word3:word4
sample output
WordOne:somenumber:wordThree:wordFour*
You can find multiple patterns with egrep:
egrep -i -w "${word1}|${word2}|${word3}|${word4}" $(find path/to/file -name '*.txt')
Let me give you a general approach:
Look for word1
AND word2
in a file:
grep "word1" file | grep "word2"
Look for word1
OR word2
in a file:
grep -E "word1|word2" file.
Let's make an exercise out of this:
Look for word1
AND ( word2
OR word3
) in a file:
grep "word1" file | grep -E "word2|word3"
As you see, AND
can be achieved, using a pipe. OR
can be achieved using extended grep ( grep -E
, sometimes abbreviated as egrep
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.