Search code examples
linuxbashshellgrepcut

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.


Solution

  • 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.