'Move last part of a file name to the begin
I would like to modify the name of several files in a folder. The name are in this format:
Name_name_name_name_XXXX.fa
I would like:
XXXX_Name_name_name_name.fa
I tired using
for f in *.fa; do mv "${f/.fa/Name_name_name_name.fa}";done
output Name_name_name_name_XXXX_Name_name_name_name.fa
and then
for f in *.fa; do mv "${f/Name_name_name_name_//}"; done
to remove the 4 name_name. but it didnt work.
Any idea how to do it?
Solution 1:[1]
You can use sed:
for f in *.fa; do
mv "$f" $(sed -E 's/^(.+)_([^.]+)\./\2_\1./' <<< "$f")
done
sed command uses 2 capture groups. 1st group contains string before last underscore and 2nd group contains XXXX part (part between last _` and dot).
Solution 2:[2]
Try this using perl's rename in just one command using regex capture groups:
rename -n 's/(.*?)_([^_]+)\.fa$/$2_$1/' *.fa
(remove -n switch when your tests are OK)
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 like
.../rename: 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's rename command.
If you don't have this command, search your package manager to install it or do it manually
Last but not least, 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 | anubhava |
| Solution 2 | Glorfindel |
