Search code examples
bashbatch-rename

Batch removing leading dash in file names in Bash


$ ls -l
-rw-r--r--@ 1 ywang  Users  6156 Aug 16 14:38 -STEST.20140728.151116.pgp
-rw-r--r--@ 1 ywang  Users  2756 Aug 16 14:38 -STEST.20140728.152042.pgp
-rw-r--r--@ 1 ywang  Users  3424 Aug 16 14:38 -STEST.20140729.141735.pgp
-rw-r--r--@ 1 ywang  Users  2439 Aug 16 14:38 -STEST.20140729.142515.pgp
-rw-r--r--@ 1 ywang  Users  2672 Aug 16 14:38 -STEST.20140730.125115.pgp
-rw-r--r--@ 1 ywang  Users  2391 Aug 16 14:38 -STEST.20140730.125556.pgp

Hi, I've tried multiple ways, e.g. looping through the file and do mv one by one. However, I wasn't successful as the caveat was that mv interprets the leading dash as a parameter to itself and backslash escaping doesn't seem to work when combining with the wildcard *.

Any ideas how it can be done in a oneliner in Bash? Thanks!


Solution

  • You can use:

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

    It is important to use ./-* for globbing so that shell doesn't interpret - as command option.