Parallelize repetitive tasks on list of files
suggest changeMany repetitive jobs can be performed more efficiently if you use more of your computer’s resources (that is, CPUs and RAM). Below is an example of running multiple jobs in parallel.
Suppose you have a list of files, say output from ls. Also suppose these files are bz2-compressed and the following tasks need to be run on them.
- Decompress the bz2 files using
bzcatto stdout - Grep (e.g. filter) lines with specific keyword(s) using
grep <some key word> - Pipe the output to be concatenated into one single gzipped file using
gzip
Running this using a while-loop may look like this
filenames="file_list.txt"
while read -r line
do
name="$line"
## grab lines with puppies in them
bzcat "$line" | grep puppies | gzip >> output.gz
done < "$filenames"
Using GNU Parallel, we can run 3 parallel jobs at once by simply doing
parallel -j 3 "bzcat {} | grep puppies" :::: "$filenames" | gzip > output.gz
This command is simple, concise, and more efficient when the number of files and the file size are large. The jobs are started by parallel. The option -j 3 launches 3 parallel jobs, and :::: reads the input file names from $filenames. The output is piped to gzip > output.gz. ::: would word-split the names, so it is the wrong operator when the list is in a file.