Вопрос

The code below doesn't work in bashrc but works in terminal with other arguments null.

search () {
        find $1 -type f | egrep '(.$2|.$3|.$4|.$5|.$6|.$7|.$8|.$9|.$10)'
}
Это было полезно?

Решение

Write this:

search() {
  find "$1" -type f \( -true \
    -o -name "*$2*" \
    -o -name "*$3*" \
    -o -name "*$4*" \
    -o -name "*$5*" \
    -o -name "*$6*" \
    -o -name "*$7*" \
    -o -name "*$8*" \
    -o -name "*$9*" \
    -o -name "*$10*" \
  \)
}
  1. As @chepner points out, the single quotes prevent the parameters from expanding. Use double quotes.
  2. The egrep will create a line-based match result, which is less precise than the above. It's also slower.

If the above statements are not exactly what you need, keep in mind GNU find has regular expression predicates in addition to -name's pattern matching. There's no need to pipe to grep. You can expand the above function to take an unlimited number of arguments by constructing the arguments to find, such as in this answer.

Другие советы

I didn't know that the egrep get the literal text $2 instead of argument. I solved with this code:

search-type () {
  case "$#" in
       1) echo "Missing arguments";;
       2) find $1 -type f | egrep '(.'$2')';;
       3) find $1 -type f | egrep '(.'$2'|.'$3')';;
       4) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4')';;
       5) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5')';;
       6) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5'|.'$6')';;
       7) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5'|.'$6'|.'$7')';;
       8) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5'|.'$6'|.'$7'|.'$8')';;
       9) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5'|.'$6'|.'$7'|.'$8'|.'$9')';;
      10) find $1 -type f | egrep '(.'$2'|.'$3'|.'$4'|.'$5'|.'$6'|.'$7'|.'$8'|.'$9'|.'$10')';;
      11) echo "Many arguments";;
  esac;
}

The @kojiro code doesn't work.

Is it possible to simplify this code with regex?

Thank you guys!

I change the code for the something more simple and clear; and works with any quantity of parameters.

search-type() {
    # Flags
    flag=0
    fld=1
    for x in "$@"
    do
        # The first parameter is the directory; ignored!
        if [ $fld = 1 ]; then
            fld=0
        else
            # Verify if have more than one file
            if [ $flag = 0 ]; then
                cmd='-name '$x
                flag=1
            else
                cmd+=' -o -name '$x
            fi
        fi
    done
    find $1 -type f $cmd;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top