I have a series of files named KLLxxx (the x represents numbers). They're text files but have no file extension to them. Just files that say KLL followed by three digits. I want them all to end with the file extension .fastq. Such as KLL123 -> KLL123.fastq.

So I tried using this command

mv KLL* KLL*.fastq

But I keep on getting the error message:

mv: target 'KLL067.fastq' is not a directory

I know about the rename command function, but I've never used Perl before so I don't know how to approach this. I know this is a basic question, but this is my first time trying out Linux.

up vote 3 down vote accepted

Running the following find command in the directory you are looking at will do the trick:

find . -name 'KLL[0-9][0-9][0-9]' -exec sh -c 'mv $0 $0.fastq' {} \;

Which will add the extension .fastq to any file name starting with KLL followed by three digits.

  • 3
    There's no need for the sh invocation: "-exec mv {} {}.fastq" by itself works and doesn't spin up a whole new shell for each file. And, of course, weird things will happen if any of the KLL files have "weird" characters in their names (eg., spaces, tabs, slashes). – minnmass Nov 6 '15 at 16:56
  • 2
    ... just something for the OP to keep in mind when their requirement changes next week is all. – minnmass Nov 6 '15 at 19:32

prename... rename with Perl expressions. The following command takes the list of files (KLL*), and for each one, it grabs the entire name of KLL plus three numbers (KLL\d{3})) and saves that into the special named $1 variable. the s at the beginning of the expression means 'substitute' what's between the first two // with what is between the 2nd set, which is the full filename in $1 and append .fastq to it.

prename 's/(KLL\d{3})/$1.fastq/' KLL*
  • Use 's/(KLL\d{3})$/$1.fastq/' - otherwise it will rename KLL* files that have already been renamed, or with extra chars after the 3 digits. – cas Nov 6 '15 at 23:23

many possible solutions here, this should be one:

for f in KLL*; do mv "$f" "$f.fastq"; done
  • 1
    for f in KLL[0-9][0-9][0-9] – rackandboneman Nov 6 '15 at 21:06

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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