Need help matching a mattern using grep/egrep in bash scripting

后端 未结 3 1336
面向向阳花
面向向阳花 2021-01-22 21:58

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 $         


        
相关标签:
3条回答
  • 2021-01-22 22:14

    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.

    0 讨论(0)
  • 2021-01-22 22:20

    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.

    0 讨论(0)
  • 2021-01-22 22:20

    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.

    0 讨论(0)
提交回复
热议问题