Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming using capture groups in Bash

Tags:

regex

bash

I would like to rename several files of the format

libabc-x86_64-gnu-linux.a
libasdfgh-x86-gnu-linux.a

all to the format

libabc.a
libasdfgh.a

using Bash. I have written the regex (libpj[^-]*).*, which should leave the interesting part in capture group 1. So I tried to use parameter substitution with Bash:

for i in `ls *.a`; do mv "$i" "${i/(lib[^-]*).*/\1}"; done

But Bash gives many errors of the form

mv: 'libabc-x86_64-gnu-linux.a' and 'libabc-x86_64-gnu-linux.a' are the same file

implying that the regex is somehow not matching, even though I have confirmed that it does with several utilities, especially the very excellent RegExr. What am I doing wrong? Does Bash have trouble with capture groups?

like image 345
George Hilliard Avatar asked Jul 09 '14 19:07

George Hilliard


1 Answers

You can use:

for i in *.a; do
   mv "$i" "${i%%-*}.a"
done

%% will remove a matching suffix pattern; in this case, it removes -*, or everything starting with the first -.

like image 103
anubhava Avatar answered Nov 05 '22 18:11

anubhava