2

I am writing a small shell script to receive an input and match against a text file.

However, the input would be a bigger string than the string in the file, against which I want a match.

User input:

abc-de-ef-gh1

Text in file:

This is test,-de-ef-gh,This is test

I want a positive result if I grep user-input with existing file.

How can I achieve this? I couldn't do it with grep.

6
  • 2
    how about echo "user input" | grep -f pattern_file
    – Kamaraj
    Aug 31, 2018 at 9:09
  • Kamaraj - it doesn't work.
    – Novice
    Aug 31, 2018 at 9:15
  • 1
    If the user input and the pattern are as in the question, then the comment of @Kamaraj will work. So your problem is not reproducible. Please give exact input and patterns. "It doesn't work" will not help us to help you.
    – chaos
    Aug 31, 2018 at 9:37
  • Apologies as I was unclear. Edited the question.
    – Novice
    Aug 31, 2018 at 9:54
  • 1
    This question is unclear. I sort-of understand it, but not clearly enough for it to be answerable.  @Novice: Do you want to match a line that contains abc-d-ef-gh1? How about f-gh? How about -gh1? How about gh or 1?  Describe the processes by which you would answer those questions; i.e., describe the rules that determine whether a string should match a line. Please do not respond in comments; edit your question to make it clearer and more complete. Sep 2, 2018 at 20:59

2 Answers 2

1

You have a file with patterns. grep can read the patterns with its -f option. If you want to check whether a string, $input, matches a pattern in patterns.txt, you may do

printf '%s\n' "$input" |
if grep -q -f patterns.txt; then
    echo 'matches'
else
    echo 'does not match'
fi

This would run grep over the contents of the string with the patterns in patterns.txt. In bash you could instead use a here-string:

if grep -q -f patterns.txt <<<"$input"; then
    echo 'matches'
else
    echo 'does not match'
fi

The -q stops grep from producing output (we're only interested in the exit status).

If the patterns are fixed strings (not regular expressions), use -F with grep in addition to the other flags (grep -qF -f ...).

0

Using bash, cut and grep:

read -p "Hey user, input something: " $n
printf "Match "
grep -m 1 -q -f <(cut -d, -f2 file) <<< "$n" || printf "not "
printf "found.\n"

Notes:

  • It's impossible to search for a longer string in a shorter, but this is really about finding whether shorter strings in file match a longer string.
  • cut is used to extract the middle field from file
  • grep searches for that middle field in the user input string.
  • printf provides some feedback.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .