I have a question about how to move files to specific folders according to their key words. Say, I have a bunch of files: R01.fastq.gz R02.fastq.gz R03.fastq.gz R04.fastq.gz ... and I have a buch of folder: data01 data02 data03 data04 ... I want to put R01.fastq.gz to data01, R02.fastq.gz to data02, R03.fastq.gz to data03, R04.fastq.gz to data04 ... So how to use a loop script to do it? Thanks a lot!

  • What have you tried so far? – bu5hman Nov 4 '19 at 18:03
# use brace expansion to create a list 00,01,02,[...] 98,99
for i in {0..9}{0..9} ; do
  # defining file and directory as vars as we will use them a couple of times each
  # if F does not exist, or is not a file, do nothing
  [ -f $F ] || continue
  # create any needed directories and move files if created OK (mkdir
  # will fail if D exists but is not a directory)
  mkdir -p $D && mv $F $D
  • Thank you very much, so what does '[ -f $F ] || continue' mean? Could you explain this part a little bit? – Jiang Xu Nov 4 '19 at 18:41
  • It makes it skip the iteration of the loop when F doesn’t exist as a file. – bxm Nov 4 '19 at 19:02
  • It could otherwise have been written: ! test -f $F && continue – bxm Nov 4 '19 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.