This is in continuation of Storing array as Environment variable to non-interactive shell - Unix & Linux Stack Exchange. Kusalananda, asked me to ask another question.
I want to find all markdown files that contain a particular regex match, and then sort the output with the files (that contain the most search term) in increasing order.
GREP(){
export Regex
xargs -0 -I "{}" bash -c 'grep "${GrepOption[@]}" --only-matching --with-filename --extended-regexp --regexp="${Regex}" "${1}" 2> /dev/null | wc -l | xargs printf "${1}:%s\n" ' _ "{}" \;
}
find . -name "*.md" -print0 | GREP | grep -v ':0$' | sort -n -r -k2 -t:
The user inputs "${Regex}". Here GrepOptions are array of options that depends on the user input. For example GrepOptions can be GrepOptions=("--ignore-case")
or it can be some other array of grep options.
But I am unable to have the array GrepOptions
be available in the subshell environment.
Any suggestions?
grepOptions
need to be an array? Doesn't the problem go away if you just useGrepOptions="--ignore-case --something-else"
and then runbash -c 'grep $grepOptions
? Do you control the values that can be stored there? – terdon Feb 26 '21 at 16:45grep ""
– Porcupine Feb 26 '21 at 16:52/bin/grep: unrecognized option '--with-filename --line-number'
– Porcupine Feb 26 '21 at 16:55GrepOptions
(in the text) versusGrepOption
(in the code)? – Jeff Schaller Feb 26 '21 at 18:18