Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cat multiple files from a list of files in Bash?

Tags:

file

bash

loops

I have a text file that holds a list of files. I want to cat their contents together. What is the best way to do this? I was doing something like this but it seems overly complex:

let count=0
while read -r LINE
do
    [[ "$line" =~ ^#.*$ ]] && continue
    if [ $count -ne 0 ] ; then
        file="$LINE"
        while read PLINE
        do
            echo $PLINE | cat - myfilejs > /tmp/out && mv /tmp/out myfile.js
        done < $file
    fi
    let count++
done < tmp

I was skipping commented lines and running into issues. There has to be a better way to do this, without two loops. Thanks!

like image 757
user1470511 Avatar asked Jul 23 '12 19:07

user1470511


2 Answers

xargs cat < files

The advantage of xargs over $(cat) is that cat expands to a huge list of arguments which could fail if you have a lot of files in the list due to Linux' maximum command line length.

Example without caring about #:

printf 'a\nb\nc\n' > files
printf '12\n3\n' > a
printf '4\n56\n' > b
printf  '8\n9\n' > c
xargs cat < files

Output:

12
3
4
56
8
9

More specific example ignoring # as requested by OP:

printf 'a\nb\n#c\n' > files
printf '12\n3\n' > a
printf '4\n56\n' > b
printf  '8\n9\n' > c
grep -v '^#' files | xargs cat

Output:

12
3
4
56

Related: How to pipe list of files returned by find command to cat to view all the files


Or in a simple command

cat $(grep -v '^#' files) > output
like image 31
Bernhard Avatar answered Sep 20 '22 11:09

Bernhard