将文件类型传递给 bash 函数并调用 find

将文件类型传递给 bash 函数并调用 find

我有以下 bash 函数可以在两个行号之间打印,用于在特定目录中递归地监视文件类型 .texi 和 .org 的文件。

我希望能够提供文件扩展名以使用用作分隔符的-e选项进行搜索,。示例:-e el,texi,org

print-region ()
{

  # Process command line options
  shortopts="hvd:e:p:q:"
  longopts="help,version,directory:,extension:,startline:,stoplinene:,"

  opts=$(getopt -o "$shortopts" -l "$longopts" -n "$(basename $0)" -- "$@")
  if [ $? -eq 0 ]; then
    eval "set -- ${opts}"
    while [ $# -gt 0 ]; do
      case "$1" in
        --)
          shift;  break  ;;
        -h|-\?|--help)
          help=1
      local -r f=0
      break
      ;;
        -v|--version)
      version=1;  shift;  break  ;;
        -d|--directory)
      local -r dir=$2
      shift 2
      ;;
        -e|--extension)
      fltype=$2
      shift 2
      ;;
        -p|--startline)
      local -r na=$2;  shift 2  ;;
        -q|--stopline)
      local -r nb=$2;  shift 2  ;;
      esac
    done
  else
    shorthelp=1 # getopt returned (and reported) an error.
  fi

  if [[ $na =~ ^[[:digit:]]+$ ]] && [[ $nb =~ ^[[:digit:]]+$ ]]  \
  && [[ -d $dir ]]; then
    
    find "$dir" \( -name \*.org -o -name \*.texi \)  \
      -exec awk -v a="$na" -v b="$nb"                \
            'FNR == 1 {s="\n==> "FILENAME" <==\n"; f = 0}
             FNR == a {print s; f = 1}
             f {print; if (FNR == b) nextfile}' {} +
  fi
}

答案1

已经初步尝试了解决方案,并且非常感谢评论。祝贺。

  str=$(echo $fltype | tr "," "\n")

  nmser=( '(' )
  for ext in $str; do
    nmser+=( -name "*.$ext" -o )
  done
  nmser[${#nmser[@]}-1]=')'
  
  printf "nmser:\n"
  for i in ${nmser[@]}; do echo $i; done

  if [[ $na =~ ^[[:digit:]]+$ ]] && [[ $nb =~ ^[[:digit:]]+$ ]]  \
  && [[ -d $dir ]]; then

    # `-exec` avoids problems with too many file matches 
    # `nextfile` stops processing the current input file.  
    #find "$dir" \( -name \*.org -o -name \*.texi \)  \
    
    find "$dir" "${nmser[@]}"  \

相关内容