mukesh
mukesh

Reputation: 11

How to use xargs on an array of files

I want to store the find command output in a variable and use it many times as find command consumes time.

abc=`find . -maxdepth 3 -type f -name "abc.txt"`

echo "${abc[*]}" | xargs grep -l "somestring1"
echo "${abc[*]}" | xargs grep -l "somestring2"
echo "${abc[*]}" | xargs grep -l "somestring3"

But it only greps on the first element of array abc.

Upvotes: 1

Views: 836

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

Since you're using nonstandard -maxdepth, I'm assuming non-standard find that handles the -print0 predicate, so as to safely build an array:

abc=()
while IFS= read -r -d '' f; do
    abc+=( "$f" )
done < <(find . -maxdepth 3 -type f -name "abc.txt" -print0)

There you have an array abc.

Now, you can safely pass the array abc as arguments to grep:

grep -l "somestring1" "${abc[@]}"
grep -l "somestring2" "${abc[@]}"
grep -l "somestring3" "${abc[@]}"

Note 1. In your code, abc is not an array.

Note 2. I have no idea why you say your code doesn't work… it should work (provided you have nice filenames without spaces and quotes); maybe you're not showing the full code?

Upvotes: 4

Related Questions