cat multiple files based on ID in filename

浪子不回头ぞ 提交于 2020-06-01 07:20:09

问题


I would like to combine files with similar ID before first underscore into one file using cat. How do I do this for multiple files like below?
Thought of something like this:

for f in *.R1.fastq.gz; do cat "$f" > "${f%}.fastq.gz"; done

in

9989_L004_R1.fastq.gz
9989_L005_R1.fastq.gz
9989_L009_R1.fastq.gz
9873_L008_R1.fastq.gz
9873_L005_R1.fastq.gz
9873_L001_R1.fastq.gz

out

9989.fastq.gz
9873.fastq.gz

回答1:


for f in *_R1.fastq.gz; do cat "$f" >> "${f%%_*}.fastq.gz"; done
  • >> for appending,
  • ${f%%_*} removes the longest suffix in $f matching _*.



回答2:


Here is another way:

for f in *_R1.fast1.gz; do 
   [[ -f "${f%%_*}.fastq.gz" ]] || cat ${f%%_*}_*_R1.fast1.gz > "${f%%_*}.fastq.gz"
done

or if you want to have it a bit more readable:

for f in *_R1.fast1.gz; do 
   key="${f%%_*}"
   [[ -f "${key}.fastq.gz" ]] || cat ${key}_*_R1.fast1.gz > "${key}.fastq.gz"
done


来源:https://stackoverflow.com/questions/55650034/cat-multiple-files-based-on-id-in-filename

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!