Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing unneeded information in filename using bash script

I need to remove everything before and after a name in bash script, the following are examples

test_3123_123_testone-2.cpp
abc_3123_12312_a.cpp
johnchase_4123123123_123123123_johnc-1.cpp

I would need them simply change into

testone.cpp
a.cpp
johnc.cpp

But having trouble with regex and trying to get this setup properly, any advice would be great!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the text right before .cpp but ignoring any dashes(-2) if they exist behind it.

Do exactly that. Write it from the end.

  • "before .cpp" -> so .cpp must be last
  • "ignoring any dashes" – so there is a dash(-2)
    • "if they exist behind it" – the dash is optional
  • "the text" – so match the text.
var=test_3123_123_testone-2.cpp
[[ "$var" =~ ([^_-]*)(-[0-9]+)?.cpp$ ]]
echo ${BASH_REMATCH[1]}.cpp
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading