寻求Bash单行命令:合并含数字的motif文件至output.txt
Hey Darren, great question! Let's break down how to solve both of your Bash command issues and get those motif files merged into output.txt smoothly.
Solution 1: Basic, Compatible Command (No Special Shell Settings)
This directly addresses your first problem by matching both 1-digit and 2-digit numbered files explicitly:
cat motif[0-9].motif motif[0-9][0-9].motif >> output.txt
- How it works:
motif[0-9].motifmatches all files with a single digit (likemotif1.motif,motif9.motif)motif[0-9][0-9].motifmatches all files with two digits (likemotif10.motif,motif20.motif)- Bash automatically expands these patterns to all matching files, so you don't need to know how many files exist upfront. The
>>appends all their content tooutput.txt.
Solution 2: Concise Command (Matches Any Digit Length)
If you want to match files with any number of digits (not just 1 or 2), you can use Bash's extended globbing. Wrap it in a subshell to avoid changing your current shell's settings, which is perfect for embedding in a longer pipeline:
(shopt -s extglob; cat motif+([0-9]).motif) >> output.txt
shopt -s extglobenables extended globbing temporarily in the subshell+([0-9])matches one or more digits, so it covers 1-digit, 2-digit, or even longer numbers if they ever appear.
Solution 3: Merge in Numeric Order (Avoid Dictionary Sorting)
By default, Bash's globbing sorts files lexicographically (so motif10.motif comes before motif2.motif). If you need to merge files in actual numeric order (1, 2, ..., 9, 10, ..., 20), use this safer, sorted approach:
find . -maxdepth 1 -type f -name 'motif[0-9]*.motif' | sort -V | xargs cat >> output.txt
find . -maxdepth 1limits the search to the current directory (no subfolders)sort -Vsorts filenames by version number (i.e., numeric order)xargs catpasses the sorted filenames tocatto merge their content.
All these commands are single-line and can be easily embedded into your longer pipeline. Pick the one that fits your environment and sorting needs best!
内容的提问来源于stack exchange,提问作者Darren

