Saturday 2 September 2017

bash - Unix: Files starting with a dash, -


Ok, I have a bunch of files starting with a dash, -. Which is not so good... and I want to rename them. In my particular case I would just like to put a character in front of them.


I found the following line that should work, but because of it dash it doesn't:


for file in -N*.ext; do mv $file x$file; done

If I put an echo in front of the mv I get a bunch of


mv -N1.ext x-f1.ext
mv -N2.ext x-f2.ext

Which is correct, except of course it will think the first filename is options. So when I remove the echo and run it I just get a bunch of


mv: illegal option -- N

I have tried to change it to


for file in -N*.ext; do mv "$file" "x$file"; done

but the quotes are just ignored it seems. Tried to use single quotes, but then the variable wasn't expanded... What do I do here?


Update: I have now also tried to quote the quotes. Like this:


for file in -N*.ext; do mv '"'$file'"' '"'x$file'"'; done

And when I echo that, it looks correct, but when I actually run it I just get


mv: rename "-N1.ext" to "x-n1.ext":: No such file or directory

I have just no clue how to do this now... sigh



Answer



You need to use the keyword -- to tell the mv command that the arguments are not to be interpreted as options. Watch:


$ mv -N1.ext x-f1.ext
mv: invalid option -- N
Try `mv --help' for more information.

$ mv -- -N1.ext x-f1.ext
$ ls
x-f1.ext

Use -- after all the options on the commandline. Eg, if you're trying to use the -i option to mv, it would go before --:


mv -i -- -filename-begins-with-dash newfilename

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...