简体   繁体   English

如何在文件数组上使用xargs

[英]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. 我想将find命令的输出存储在一个变量中,并多次使用它,因为find命令会消耗时间。

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. 但是它仅对数组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 : 由于您使用的非标准-maxdepth ,我假定非标准find一个处理-print0谓词,以便安全地创建数组

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 . 那里有一个数组 abc

Now, you can safely pass the array abc as arguments to grep : 现在,您可以安全地将数组abc作为参数传递给grep

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

Note 1. In your code, abc is not an array. 注意1.在您的代码中, abc不是数组。

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); 注2:我不知道为什么您说您的代码不起作用……它应该起作用(前提是您的文件名没有空格和引号); maybe you're not showing the full code? 也许您没有显示完整的代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 允许用户在选择文件到数组后完成并行 / xargs 命令(功能); 在 printf 脚本中正确引用 NULL - allow user to complete parallel / xargs command (function) after selecting files into array; quoting nuls correctly in printf script 如何上传文件数组? - How to upload an array of files? 在Shell中,如何制作文件数组,以及如何使用它将其与另一个文件进行比较? - In Shell, how can I make an array of files and how do I use it to then compare it to another file? 如何使用numpy.savez将带有子数组的数组保存到单独的.npy文件中 - How to use numpy.savez to save array with subarrays into separate .npy files 如何使用字符串数组使用用户定义的 function 从文件中读取多行 - How to use string array to read multiple lines from files using an user defined function 如何加载带有图像链接的XML文件以用于2D JavaScript数组? - How to load XML files with links to images for use in a 2D JavaScript Array? 如何在数组中使用数组变量? - How to use array variable in array? 如何使用字符串数组的数组 - How to use Array of Array of String 如何获取要上传的文件数组 - How to get an array of files to upload 如何使用带有字符串的数组 - How to use an array with a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM