简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM