How to mv (rename) a file that stats with dash if we get the file from a variable?

46 Views Asked by At

I am trying to rename a file using the move (mv) command

$ls

-0
-1
-2

to

000.json
001.json
002.json

the code I tried

for i in -*; do
  N=3
  echo mv -v -- "\"""$i""\"" "$(echo "$i" | sed -r ":r;s/\b[0-9]{1,$((N - 1))}\b/0&/g;tr" | sed "s/-//" | sed "s/$/.json/")"
  mv -v -- "\"""$i""\"" "$(echo "$i" | sed -r ":r;s/\b[0-9]{1,$((N - 1))}\b/0&/g;tr" | sed "s/-//" | sed "s/$/.json/")"
done

this code outputs

mv -v -- "-0" 000.json
mv: cannot stat '"-0"': No such file or directory
mv -v -- "-1" 001.json
mv: cannot stat '"-1"': No such file or directory
mv -v -- "-2" 002.json
mv: cannot stat '"-2"': No such file or directory

If I try to execute mv -v -- "-0" 000.json this works. but when I try to do it with mv -v -- "\"""$i""\"" "$(echo "$i" | sed -r ":r;s/\b[0-9]{1,$((N - 1))}\b/0&/g;tr" | sed "s/-//" | sed "s/$/.json/")". It won't work.

Can anybody help me fixing mv -v -- "\"""$i""\"" ... this part of command Where in "\"""$i""\"" I am just trying to add quotes? So It give No such file or directory.

1

There are 1 best solutions below

0
Gilles Quénot On

Basically, to avoid errors on files starting with a dash -, use:

command -- *
command ./*

Using Perl's rename:

Remove -n switch, aka dry-run when your attempts are satisfactory to rename for real.

rename -n 's/-(\d+)/sprintf("%.3d%s", $1, ".json")/e' ./*
rename(-0, 000.json)
rename(-1, 001.json)
rename(-2, 002.json)