user974887 user974887 - 4 months ago 18
Linux Question

How do I sort a list of files and concatenate the contents in bash?

This works:

find . -name "*.1" -print0 | xargs -0 cat > list.txt

But when I try to sort the the filenames, remove the newline the list of filenames that are piped to cat look identical to the previous but sorted:

find . -name "*.1" | sort | sed ':a;N;$!ba;s/\n//g' | xargs -0 cat > list.txt

However cat returns this error:

: No such file or directory


Your xargs statement is expecting null terminated entries.

find . -name '*.1' | sort | tr '\n' ' ' | xargs cat > list.txt

If your filenames or directories have spaces, then yes, use the null terminated way.