Search code examples
linuxbashcat

Printing contents of several files after listing them with ls


Although it seems to be a simple task, I am struggling to print the contents of several files that have been filtered in this way:

$ ls *_pattern_*
a_pattern_a
b_pattern_b
c_pattern_c
total_pattern_total

ls *_pattern_* | grep -v total
a_pattern_a
b_pattern_b
c_pattern_c

ls *_pattern_* | grep -v total | xargs cat
cat: 'a_pattern_a': No such file or directory
cat: 'b_pattern_b': No such file or directory
cat: 'c_pattern_c': No such file or directory

Perhaps I need to buy some more coffee... Any hints are much appreciated.


Solution

  • find *_pattern_* -prune -type f ! -name '*total*' -exec cat {} +
    
    • -prune avoids descending to subdirectories if any of *_pattern_* is a directory
    • -type f handles no matches at all or match being a directory

    The single-quotes in the sample error messages indicate that ls escaped some characters in the filename. Consider:

    $ touch a! a\ b a_c
    $ ls a*
    'a b'  'a!'   a_c