Ubuntu – How to copy the contents of every file in a list into another file

command linecopyfilenamefiles

I have a list of filenames inside a file called list_of_files.txt.

I want to copy the contents of each file in that list into another file called all_compounds.sdf.

How should I do this from the command line?

Best Answer

Don't use simple command substitution to get filenames (that could easily break with spaces and other special characters). Use something like xargs:

xargs -d '\n' -a list_of_files.txt cat > all_compounds.sdf

Or a while read loop:

while IFS= read -r file; do cat "$file"; done < list_of_files.txt > all_compounds.sdf

To use command substitution safely, at least set IFS to just the newline and disable globbing (wildcard expansion):

(set -f; IFS=$'\n'; cat $(cat list_of_files.txt) > all_compounds.sdf)

The surrounding parentheses () are to run this in a subshell, so that your current shell isn't affected by these changes.