Search code examples
bashrename

I need to remove characters before the first dash of my filenames in Linux


I have multiple filenames in a directory which are delimited by dash. they have different length and characters. I want to delete everything until the first occurrence of dash.

Original files

NXNX LXMXTXD-X003452030-09 Feb 2024.pdf
Y LXD-X022203613-04 Dec 2023.pdf
TXR BXRXEX-X012306784-11 Feb 2022.pdf
Y LXMXTXD-X02503742-09 Feb 2024.pdf

Expected output where everything before the first dash and dash itself is removed.

X003452030-09 Feb 2024.pdf
X022203613-04 Dec 2023.pdf
X012306784-11 Feb 2022.pdf
X02503742-09 Feb 2024.pdf

Thanks!

I have tried bash with mv "$f" "${f#??}" but this deletes characters which I cannot control to stop on the occurrence of first dash.

also tried rename but seems my OS not supporting it.


Solution

  • You probably meant

    mv "$f" "${f#*-}"
    

    ${f#??} just remove the 2 first chars. What is after # in such expression is a pattern (like you use to target several files, with some * and ? in it). ? means "any char". So ?? is a pair of them. So ${f#??} is f minus the first two chars.

    *- means "as many char as you want, then a dash. After ## it means "the biggest prefix that is made of some chars then a dash". After a single # it means "the smallest prefix that is made of some chars then a dash".

    So ${f#*-} is f minus the smallest suffix made of chars then a dash. Said otherwise, f minus every thing that is before the first dash, that first dash included.