Mac will append a ' 2' (note the space) to the end of a file/folder that is a copy of another file/folder inside the same directory... I was wondering if anybody knows how to batch remove/rename this ' 2' from a directory of folders from Terminal.
-
How do you want to rename the files? Just remove the trailing " 2" or something else?– nohillside ♦Commented Jun 3, 2015 at 13:09
-
yes, I want to remove the trailing " 2"... for directories inside of a directory ie... Music/Tom Petty 2/ ... ( not files or the files within the renamed directory )– Ken McLeodCommented Jun 3, 2015 at 13:51
2 Answers
Use find
to locate files like this way:
find . -name "* 2" -exec rm -r "{}" \;
This command will search for files and folders from where your are .
with name "* 2"
and delete every result -exec rm {}
.
If you want to rename directories:
find . -name "* 2" -type d -exec rename 's/ 2/-copy/g' {} \;
As other command, locate only folders with name "*.2"
and rename it replacing 2
with -copy
.
If you don't have rename
installed, you can also use
find . -name "* 2" -type d -exec bash -c '[[ -x "${0/ 2/-copy}" ]] || mv "$0" "${0/ 2/-copy}"' {} \;
(The [[ -x
part tests whether a file/folder already exists).
-
but, what if you are trying to rename ( not delete ) directories ( not files ). Commented Jun 3, 2015 at 13:02
-
-
The OP wants to rename files/folders, not only delete them– nohillside ♦Commented Jun 3, 2015 at 13:09
-
@patrix read carefully: "how to batch remove/rename". This usually means one or another, isn't it?– jherranCommented Jun 3, 2015 at 13:12
-
Well, just in case anybody else comes up with this same question... I found a simple resolution.... if you have Homebrew
brew install rename
...
rename -s " 2" '' *
turns Music/Tom Petty 2 into Music/Tom Petty. Likewise, if you wanted to add something to your directory names with a similar ending like ' 2', you could...
rename -s " 2" '-blob' *
... Music/Tom Petty 2/
becomes
Music/Tom Petty-blob/