Rename all the files within a folder with prefix “Unix_” i.e. suppose a folder has two files a.txt and b.pdf than they both should be renamed from a single command to Unix_a.txt and Unix_b.pdf
5 Answers
The rename command can rename files using regular expressions, which makes it very powerful. In your case, you could do
rename 's/(.*)/Unix_$1/' *.txt
-
... and the pdf-File? :)user unknown– user unknown2011-05-15 03:40:22 +00:00Commented May 15, 2011 at 3:40
-
rename 's/(.*)/Unix_$1/' *.pdffromnaboo– fromnaboo2012-07-03 01:51:51 +00:00Commented Jul 3, 2012 at 1:51 -
1No need to capture, just replace the beggining-of-string:
rename 's/^/Unix_/' *.pdfmmoya– mmoya2013-11-12 23:03:11 +00:00Commented Nov 12, 2013 at 23:03 -
this doesn't work for filenames starting with
-which leads to the errorUnknown option:...mcExchange– mcExchange2020-06-14 13:09:25 +00:00Commented Jun 14, 2020 at 13:09 -
@mcExchange , have you tried with
--option? Normally, all standard utilities support the end of option processing option "double-dash". Just in case, there's alsokrename, andmrename. More withapt search renameif available, including repository source lists.Serious Angel– Serious Angel2023-11-05 02:03:26 +00:00Commented Nov 5, 2023 at 2:03
With the rename utility included in the util-linux package (the one on dj_segfault's answer comes from perl), you could do rename '' Unix_ *
If you're using Zsh as your shell, you could also use the function zmv.
Add this line to your .zshrc:
autoload -U zmv
then you could run:
% zmv -W '*' 'Unix_*'
See man zshcontrib for further information.
-
The more I read about zsh, the more I like it.boehj– boehj2011-05-15 03:34:17 +00:00Commented May 15, 2011 at 3:34
Some of the other answers might be better however, if I thought that xargs deserved a mention since it is a very powerful tool (and on many systems):
In this particular you could do:
ls | xargs -n1 -I{} mv {} Unix_{}
Edit: Retracted per Gilles' comment. For this situation this solution should be considered only a hack due to the caveats as pointed out by the cited article. The other answers are much better. I still think that xargs is still a useful tool (I use it with svn status relatively frequently), but he's right, for simple execute some command on all files in a tree of directories, this isn't the answer and find is much better. (Leaving the answer since the I think the comment is good for people who'd make the same mistake).
-
2Don't parse the output of
ls.xargsis actually rarely useful, especially now thatfind … -exec … +exists.Gilles 'SO- stop being evil'– Gilles 'SO- stop being evil'2011-05-14 23:11:54 +00:00Commented May 14, 2011 at 23:11 -
Thanks @Gilles that's a good article. Edited retracting my answer.Charlie– Charlie2011-05-15 01:55:17 +00:00Commented May 15, 2011 at 1:55