Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all files with certain extension to another directory, while changing the extension

I want to copy all the files with extension aaa from directory a to directory b, replacing the extension to bbb. I tried to do something like this:

ls a | grep \.bla$ | cut --delimiter=. -f 1 | xargs cp a/{}.aaa b/{}.bbb

But it's really off. I want a oneliner, and not a bash script.

like image 358
user972014 Avatar asked Apr 07 '15 12:04

user972014


People also ask

How do I copy a file with a specific extension in Linux?

Copy Files with Specific File Extensions To copy folders, we have to specify the '-r' (recursive) flag. Recursive means that all the files in that folder, the files in the subfolders, and so on, will all be copied. However, there is no way within 'cp' to copy files of a specific extension recursively.

How do I copy multiple file extensions in Linux?

To copy multiple files you can use wildcards (cp *. extension) having same pattern. Syntax: cp *.


1 Answers

I think you make the problem a bit too complicated, if the target directory is empty, you can do this with the following one-liner:

cp a/*.aaa b; rename 's/aaa$/bbb/' b/*.aaa

The script uses two commands with a ; in between to execute the second after the first.

cp a/*.aaa b

copies all the files with the pattern a/*.aaa to the b directory. By doing this with a single call, the command will also be more efficient than using a pipe.

Next rename is a utility tool to perform a regex find-and-replace on the file names. By specifying b/*.aaa you will rename all files in b with the *.aaa regex. Now you only need to specify what to replace, this is done with the regex:

s/aaa$/bbb/

aaa$ means the last three characters must be aaa and you replace them with bbb for each file.

like image 151
Willem Van Onsem Avatar answered Sep 25 '22 14:09

Willem Van Onsem