I have many files with names in the form


where "pattern" is fixed, but there are very many usernames, each with several files (i.e. values of 'suffix'). I'd like concatenate each user's files into a single file, e.g.


to end up with one file per username. Each username contains two underscores_ and ends with a number, but is variable length.

  • 1
    cat *_pattern_* > username.ext
    – tachomi
    Jan 22, 2016 at 19:13
  • They're all in one directory. Each username contains exactly two underscores, so it's everything before the 3rd one. (Sorry I didn't say.)
    – Mark
    Jan 23, 2016 at 10:59
  • Yes @don, so something like a_smith_123_pattern_prog1.ext, ... a_smith_123_pattern_prog10.ext, ...z_jones_456_pattern_q5.ext,...z_jones_456_pattern_q7.ext (where a_smith_123 is the user name).
    – Mark
    Jan 23, 2016 at 16:21

2 Answers 2


Depending on how many files there are you could do something like:

for pat in *_pattern_*; do
    cat -- "$pat" >> "${pat%%_pattern_*}".ext

this will loop over all the files in this directory that contain _pattern_ and cat the contents of each appending to a file whose name is everything before _pattern_ appears in the string, then adding the .ext extension.

If there are too many files this won't work though

  • Thanks @Eric , around 10^3 files but this is perfect for what I need.
    – Mark
    Jan 23, 2016 at 16:57
cat username_pattern_* > username.ext

this will concatenate files in alphabetical or alphanumerical order of suffix portion

unless the username_pattern is not in a uniform format, i.e., either fixed length, or delimited by a special character, it should be quite easy to extract the username_pattern from the file names using cut or awk and run them thru a for loop. Not knowing the exact pattern, it is very hard to guess the specific action.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .