用给定的字符串从所有文件中创建一个文件

Making a file out of all the files with given a string

Create a file that includes the content of all the files in the current folder that has a given string (in say argument 1), the data will be in it one after the other (each file appended to the end). The name of the file will be the given string.

我想到了以下但它不起作用:

grep  * >> fnames #places all the names of the right files in a file
for x in fnames
do
  cat x >>  #concat the files from the list
done
rm fnames

同样,是否有网站解决过类似这样的练习或示例?

你可以使用 process substitution:

做这样的事情
shopt -s nullglob

while read -r file; do
    cat "$file"
done < <(grep -l "search-pattern" *) > /path/to/newfile

这是假设您的目录只有文件而没有子目录。

如果还有子目录,您将需要使用 findgrep

find . -maxdepth 1 -type f -exec grep -q "search-pattern" {} \; -print0 |
     xargs -0 cat > /path/to/newfile

怎么样(假设您不担心名称中包含空格或换行符或 shell globs/etc. 的文件,因为它们在这里无法正常工作):

for O in $(grep -l  *)
 do
   cat "$O" >> 
 done