'How can I change the order of some string in a filename

I have lots of files like these:

tf_CVBV6Z_CVSA1Z_pws2_pcc1.sac
tf_CVBV5Z_CVSA2Z_pws2_pcc1.sac
tf_CVBV4Z_CVSA3Z_pws2_pcc1.sac
tf_CVBV3Z_CVSA4Z_pws2_pcc1.sac
tf_CVBV2Z_CVSA5Z_pws2_pcc1.sac
tf_CVBV1Z_CVSA6Z_pws2_pcc1.sac

and I want to change the order to end up like this:

tf_CVSA1Z_CVBV6Z_pws2_pcc1.sac
tf_CVSA2Z_CVBV5Z_pws2_pcc1.sac
tf_CVSA3Z_CVBV4Z_pws2_pcc1.sac
tf_CVSA4Z_CVBV3Z_pws2_pcc1.sac
tf_CVSA5Z_CVBV2Z_pws2_pcc1.sac
tf_CVSA6Z_CVBV1Z_pws2_pcc1.sac

I tried the rename option but it does not work.

Any thoughts?

Thanks



Solution 1:[1]

With perl's rename :

$ rename -n 's/(CV[^_]+)_(CV[^_]+)/$2_$1/' tf_CVSA1Z_CVBV6Z_pws2_pcc1.sac
tf_CVSA1Z_CVBV6Z_pws2_pcc1.sac -> tf_CVBV6Z_CVSA1Z_pws2_pcc1.sac

Remove -n switch when the output looks good.

warning There are other tools with the same name which may or may not be able to do this, so be careful.

If you run the following command (GNU)

$ file "$(readlink -f "$(type -p rename)")"

and you have a result that contains Perl script, ASCII text executable and not containing ELF, then this seems to be the right tool =)

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo update-alternatives --set rename /path/to/rename

Replace /path/to/rename to the path of your perl rename executable.


If you don't have this command, search your package manager to install it or do it manually (no deps...)


This tool was originally written by Larry Wall, the Perl's dad.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Glorfindel