grep не принимает getopts - PullRequest
       15

grep не принимает getopts

0 голосов
/ 29 июня 2018

Есть каталог:

.
├── file4.txt
├── file5.yml
├── txt
│   ├── file1.txt
│   ├── file2.txt
│   └── file3.txt
└── yml
└── file6.yml

Некоторые файлы содержат слово hello:

>> grep -r 'hello' .

  ./file4.txt:hello
  ./yml/file6.yml:hello
  ./txt/file1.txt:hello
  ./txt/file2.txt:hello
  ./file5.yml:hello

А теперь я хочу написать скрипт, который будет искать hello в разных местах и ​​файлах, т.е.:

$ grep -EHori --exclude-dir={txt,yml} --include="*.txt" 'hello' .
  ./file4.txt:hello
$ grep -EHori --exclude-dir={txt,yml} --include="*.yml" 'hello' .
  ./file5.yml:hello
$ grep -EHori --exclude-dir={yml} --include="*.yml" 'hello' .
  ./yml/file6.yml:hello
  ./file5.yml:hello
$ grep -EHori --exclude-dir={txt} --include="*.yml" 'hello' .
  ./yml/file6.yml:hello
  ./file5.yml:hello
$ grep -EHori --exclude-dir={txt} --include="*.txt" 'hello' .
  ./file4.txt:hello
  ./txt/file1.txt:hello
  ./txt/file2.txt:hello

У меня есть:

#!/bin/bash

exclude_path="txt"
file_types="*.txt"
include_path="./"
check_path="./"

while getopts ":e:t:i:p" opt; do
    case $opt in
         e)
            exclude_path="${OPTARG}"
            ;;
         t)
            file_types="${OPTARG}"
            ;;
         i)
            include_path="${OPTARG}"
            ;;
         p)
            check_path="${OPTARG}"
    esac
done

result=$(grep -EHori --exclude-dir=$exclude_path \
    --include=$file_types 'hello' "$check_path")
echo $result

Но он не работает с несколькими значениями для exclude_path и include_path, т. Е .:

grep -r --exclude-dir={dir1,dir2,dir3} --include={type1,type2,type3} keyword /path/to/search

Также, если я использую -p, grep жалуется No such file.

$ ./grep.sh
  ./file4.txt:hello
$ ./grep.sh -t *.yml
  ./file5.yml:hello
$ ./grep.sh -p yml -t *.yml
  grep: : No such file or directory
$ ./grep.sh -t *txt,*.yml

Мне нужно сохранить result как переменную, так как я буду работать с ним дальше. Я думаю, что я должен использовать eval wtih grep и escape-переменные, но я не уверен.

Ответы [ 2 ]

0 голосов
/ 29 июня 2018

Проблема решена, работает с eval grep -EHori --exclude-dir={$exclude_path} \ --include={$file_types} 'hello' "$check_path"

0 голосов
/ 29 июня 2018

В вашем выражении getopt есть опечатка:

while getopts ":e:t:i:p" opt; do

должно быть

while getopts ":e:t:i:p:" opt; do

без последнего : p не принимает никаких аргументов, поэтому, когда вы набрали -p yml, он выполнил grep ... '' вызвать check_path="" причина OPTARG был пуст для p:

$ bash -x ./grep.sh -p yml -t '*.yml'
...
++ grep -EHori --exclude-dir=txt '--include=*.txt' hello ''
grep: : No such file or directory
...

Исправлен вывод скрипта:

$ ./grep.sh -p yml -t '*.yml'
yml/file6.yml:hello

Примечание: не забудьте правильно заключить аргументы, набрав ./grep.sh -p yml -t *.yml, вы получите ./grep.sh -p yml -t file5.yml, потому что * расширяется с помощью bash. Возможно, вы хотели заключить его в ', иначе ./grep.sh -p yml -t *.yml возвращает только пустую строку (из echo), потому что file5.yml не находится внутри yml каталога.

...