Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep array parameter of excluded files

Tags:

linux

grep

bash

I want to exclude some files from my grep command, for this I'm using parameter:

--exclude=excluded_file.ext

To make more easy to read I want to use a bash array with excluded files:

EXCLUDED_FILES=("excluded_file.ext")

Then pass ${EXCLUDED_FILES} array to grep, like:

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

How I can pass an array as parameter to grep command?

like image 878
0x3d Avatar asked Nov 29 '22 22:11

0x3d


2 Answers

Variables are not passed to programs as arguments; values are. Variables (especially arrays) are expanded by the shell into one or more words, and each word is passed as a separate argument to a program. In this specific case, the --exclude option takes a single file name as its argument, so you need to build up multiple --exclude=foo arguments from your array. One option:

for f in "${EXCLUDED_FILES[@]}"; do
    opts+=( --exclude="$f" )
done
grep -Rni "my text" "${opts[@]}"
like image 145
chepner Avatar answered Dec 18 '22 17:12

chepner


I guess you're looking for this:

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

The parameter expansion "${excluded_files[@]/#/--exclude=}" will expand to the expansion of the array excluded_files with each field prefixed with --exclude=. Look:

$ excluded_files=( '*.txt' '*.stuff' )
$ printf '%s\n' "${excluded_files[@]/#/--exclude=}"
--exclude=*.txt
--exclude=*.stuff
like image 33
gniourf_gniourf Avatar answered Dec 18 '22 18:12

gniourf_gniourf