philipp
philipp

Reputation: 16515

How to remove leading dash from filenames in Bash

I have a directory with files like:

-001.jpg
-002.jpg
...
-100.jpg

and I would like to remove the leading dash of each one.

I have tried:

rename -vn 's/^-//g' *

But I get:

Unknown option: 0
Unknown option: 0
Unknown option: 0
Unknown option: .
Unknown option: j
Unknown option: p
Unknown option: g
Unknown option: 0
Unknown option: 0

and so forth…

How can one play the trick?

Upvotes: 1

Views: 2525

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52122

With just shell parameter expansion, no external tools:

shopt -s nullglob
for f in *.jpg; do mv -- "$f" "${f#-}"; done

The nullglob shell option makes sure that *.jpg doesn't expand to anything if it doesn't match any files; "${f#-}" expands to the filename stored in f minus the leading hyphen.

mv -- is required to prevent the filename to be interpreted as an option to mv.


Not all versions of mv understand -- as the delimiter of options. It is, as fas as I can see, for example not required by POSIX. A more portable version would be to use

for f in *.jpg; do mv "./$f" "./${f#-}"; done

instead. Hat tip to Gordon Davisson for pointing it out.

Upvotes: 3

anubhava
anubhava

Reputation: 785098

- is treated as an option for rename command.

You can use rename like this:

rename -vn -- 's/^-//' *

Upvotes: 9

Related Questions