Recursively rename all files whose name starts with a dash

6,626

Solution 1

Using find and rename:

find . -iname '-*' -execdir rename -n 's:./-:./:' {} +

find . -iname '-*' matches all filenames beginning with a -, and then -execdir ... {} + runs the command with those filenames as arguments, after cding to the directory containing the files. This means that the command arguments always has filenames of the form ./-foo. Then it's easy to just match the - after the ./ in a regex.

Solution 2

I guess this should work as well

for i in $(find . -iname '-*') ; do mv $i $(echo $i | sed -e "s/-//"); done
Share:
6,626

Related videos on Youtube

jbrock
Author by

jbrock

Spanish teacher and language lab manager

Updated on September 18, 2022

Comments

  • jbrock
    jbrock almost 2 years

    In terminal I can rename a single file that starts with a dash, i.e.

    mv ./-file file
    

    I can also rename all files in a directory that start with a dash, i.e.

    for f in ./-*; do rename 's/-//' "$f"; done
    

    However, how can I do this recursively. I have tried using the find command, the rename command, and a recursive for loop. By the way, a lot of the file names have more than one dash. I would only want to remove the first dash. Thanks!

  • jbrock
    jbrock over 7 years
    Very nice. That is exactly what it seemed that needed to be done, cd to each directory that contains those files. Thanks! :)