Grep array parameter of excluded files

I want to exclude some files from my command grep, for this I use the parameter:

--exclude=excluded_file.ext

To make reading easier, I want to use a bash array with excluded files:

EXCLUDED_FILES=("excluded_file.ext")

Then pass the array $ {EXCLUDED_FILES} to grep, for example:

grep -Rni "my text" --exclude=${EXCLUDED_FILES}

How to pass an array as a parameter to a command grep?

+4
source share
5 answers

I think you are looking for this:

grep -Rni "${excluded_files[@]/#/--exclude=}" "my text"

The extension of the parameter "${excluded_files[@]/#/--exclude=}"will expand to expand the array excluded_fileswith each field with a prefix --exclude=. Take a look:

$ excluded_files=( '*.txt' '*.stuff' )
$ printf '%s\n' "${excluded_files[@]/#/--exclude=}"
--exclude=*.txt
--exclude=*.stuff
+4
source

; . ( ) ​​ , . --exclude , --exclude=foo . :

for f in "${EXCLUDED_FILES[@]}"; do
    opts+=( --exclude="$f" )
done
grep -Rni "my text" "${opts[@]}"
+7

GNU grep --exclude-from, , , , .

( ), , :

grep -Rni "my text" --exclude-from=<(printf '%s\n' "${EXCLUDED_FILES[@]}")

: , .

+2

GNU , grep find. - sort tr head/tail ? UNIX find. UNIX grep " G R egular E P rint ".

find , grep , regexp-2, , , UNIX:

findsarg=()
for f in "${EXCLUDED_FILES[@]}"
do
    findsarg+=( '!' -name "$f" )
done
find . -type f "${findsarg[@]}" -exec grep -Hni "my text" {} +

@gniourf_gniourf , .

, / .

+2

. - .

, , ( ).

grep -Rni "my text" --exclude="${EXCLUDED_FILES[*]}"

, , --exclude GNU grep . , . --exclude-from . , --exclude .

+1

Source: https://habr.com/ru/post/1665524/


All Articles