Grep multiple bash parameters

后端 未结 2 1377
再見小時候
再見小時候 2021-01-24 10:38

I\'m writing a bash script which shall search in multiple files.

The problem I\'m encountering is that I can\'t egrep an undetermined number of variables passed as param

相关标签:
2条回答
  • 2021-01-24 11:12

    A safe eval could be a good solution

    #!/bin/bash
    
    if [[ $# -gt 0 ]]; then
        TEMP=("grep" "-e" "\"\$1\"" "*")
        for (( I = 2; I <= $#; ++I )); do
            TEMP=("${TEMP[@]}" "|" "egrep" "-e" "\"\$${I}\"")
        done
        eval "${TEMP[@]}"
    fi
    

    To run it:

    bash script.sh A B C
    
    0 讨论(0)
  • 2021-01-24 11:32

    You can use recursion here to get required number of pipes:

    #!/bin/bash
    
    rec_egrep() {
        if [ $# -eq 0 ]; then
            exec cat
        elif [ $# -eq 1 ]; then
            exec egrep "$1"
        else
            local pat=$1
            shift
            egrep "$pat" | rec_egrep "$@"
        fi
    }
    
    first_arg="$1"
    shift
    grep "$first_arg" * | rec_egrep "$@"
    
    0 讨论(0)
提交回复
热议问题