search for content in files. Name of files is in another file. Format as report.

Hi I have multiple files in a folder and one file which contains a list of files (one on each line). I was to search for a string only within these files and not the whole folder. I need the output to be in the form

File1<tab>string instance 2<tab> string instance 2<tab>string instance 3
File2<Tab>string instance 1

I managed to get the output , but with each instance on a new line with the following

grep string `cat filenamelist.txt`

I need it in tabbed form, was hoping tr would do it however it made all the items on the same line including the 2 files.

grep string `cat filenamelist.txt` | tr "\n" "\t"

how can I format it the way I want without a loop?

Why without a loop?

Regards,
Alister

I thought it should be possible without a loop and i remember having done something similar before. its just driving me nuts.
If it is absolutely necessary or much simpler to use a loop i wouldnt mind it, however would be great if it was without one

Also I bet a friend it is possible :slight_smile:

What if the file doesn't contain a match? Should its file name appear in the output or not? If so, should it be followed by a tab?

Regards,
Alister

Both options are fine, however I imagine displaying a filename without any string match would be tougher. If the filename is displayed and it has no matched string it need not have a tab.

while read f; do
    { printf '%s\n' "$f"; grep 'string' "$f"; } | paste -s -
done < filenamelist.txt

For your bet:

xargs -L1 sh -c '{ printf %s\\n "$2"; grep "$1" "$2"; } | paste -s -' sh 'string' < filenamelist.txt

Perhaps the implicit looping of xargs doesn't violate any restriction.

Regards,
Alister

Thanks! I will try this out and get back to you. Is there anyway to make the

grep string `cat filelist.txt`

work the way I want it to?