Grep Array Parameter of Excluded Files

grep array parameter of excluded files

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

GREP: Excluding file names with specific pattern while including specific file extension

If you want to exclude files with any numbers in their names, modify the grep line to:

@files = grep (/^\D*\.png\z/,readdir(DIR));

This only returns file names that starts with any (or zero) non-digit characters, and is followed by a .png ending.

If you want to exclude files containing just 1-9 in their names, change the regex:

@files = grep (/^[^1-9]*\.png\z/,readdir(DIR));

Is it possible to do a grep with keywords stored in the array?

args=("key1" "key2" "key3")
pat=$(echo ${args[@]}|tr " " "|")
grep -Eow "$pat" file

Or with the shell

args=("key1" "key2" "key3")
while read -r line
do
for i in ${args[@]}
do
case "$line" in
*"$i"*) echo "found: $line";;
esac
done
done <"file"

Using array for `ls --ignore`

Here is one way of doing it without using ls and to make matters worst you're using the -al flag.

#!/usr/bin/env bash

shopt -s nullglob extglob

files=(/path/to/www/directory/!(ubuntu|test)/)

declare -p files

That will show you the files in the array assignment.

If you want to loop through the files and remove the pathname from the file name without using any external commands from the shell.

for f in "${files[@]}"; do echo "${f##*/}"; done 

Which has the same result when using basename

for f in "${files[@]}"; do var=$(basename "$f"); echo "$var"; done 

Or just do it in the array

printf '%s\n' "${files[@]##*/}"

The "${files##*/}" is a form of P.E. parameter expansion.

There is an online bash manual where you can look up P.E. see Parameter Expansion

Or the man page. see PAGER='less +/^[[:space:]]*parameter\ expansion' man bash

Look up nullglob and extglob see shell globbing

The array named files now has the data/files that you're interested in.

By default the dotfiles is not listed so you don't have to worry about it, unless dotglob is enabled which is off by default.

grep output into array

If you just need the first element (or rather line), you can use head:

`find /xyz/abc/music/ |grep def | head -n 1`

If you need access to arbitrary elements, you can store the array first, and then retrieve the element:

arr=(`find /xyz/abc/music/ |grep def`)
echo ${arr[n]}

but this will not put each line of grep output into a separate element of an array.

If you care for whole lines instead of words, you can use head and tail for this task, like so:

`find /xyz/abc/music/ |grep def | head -n line_number | tail -n 1`


Related Topics



Leave a reply



Submit