Need help matching a mattern using grep/egrep in b

2020-04-16 17:36发布

问题:

I am trying to match all characters of given string but those characters should match in the order as given to the bash script.

while [[ $# -gt 0 ]]; do
  case $1 in
       -i)
    arg=$2
    egrep "*[$arg]*" words.txt 
    shift ;;
  esac
  shift
done

$ sh match_the_pattern.sh -i aei words.txt

Should return words like

abstentious
adventitious
sacrilegiousness

If you notice, first a is matched then e and then i, all of them are in order. Plus, the whole word is matched and filtered.

回答1:

Change this:

arg=$2
egrep "*[$arg]*" words.txt

to this:

arg=$(sed 's/./.*[&]/g' <<< "$2")
grep "$arg" words.txt

If that's not all you need then edit your question to clarify your requirements and provide more truly representative sample input/output.



回答2:

You may use getopts with some bash parameter substitution to construct the query string.

#!/bin/bash
while getopts 'i:' choice
do
  case "${choice}" in
    i)
     length=${#OPTARG}
     for((count=0;count<length;count++))
     do
      if [ $count -eq 0 ]
      then 
       pattern="${pattern}.*${OPTARG:count:1}.*"
      else
       pattern="${pattern}${OPTARG:count:1}.*"
      fi
     done
    ;;    
  esac
done
# The remaining parameter should be our filename
shift $(($OPTIND - 1))
filename="$1"
# Some error checking based on the parsed values
# Ideally user input should not be trusted, so a security check should
# also be done,omitting that for brevity.
if [ -z "$pattern" ] || [ -z "$filename" ]
then
 echo "-i is must. Also, filename cannot be empty"
 echo "Run the script like ./scriptname -i 'value' -- filename"
else
 grep -i "${pattern}" "$filename"
fi

Refer this to know more on parameter substitution and this for getopts.



回答3:

Your regex is matching 'a' or 'e' or 'i' because they are in a character set ([]). I think the regular expression you are looking for is

a+.*e+.*i+.*

which matches 'a' one or more times, then anything, then 'e' one or more times, then anything, then 'i' one or more times.



标签: bash shell grep