10

How can I strip out some text from filenames in a folder?

I'm currently attempting:

rename s/"NEWER_(.*?)"//g *

But nothing it getting renamed

I have a parent folder, with a bunch of sub-folders, within are files, that OneDrive thought would be a great idea to append a " (NEWER_timestamp)" to, and I'd like to remove that.

Example File Names:

getyou.ico (NEWER_1417529079.87)
o7pm.ico (NEWER_1417529184.89)
o7th.ico (NEWER_1417529135.81)
2
  • 2
    Can you post an example filename?
    – muru
    Dec 15, 2014 at 20:42
  • sure. updated question with some
    – Kevin
    Dec 15, 2014 at 20:44

2 Answers 2

8

Try the following:

find /path/to/parrent-dir -type f -exec rename -n 's:[^/]*(.*) .*$:$1:' {} +

./o7th.ico (NEWER_1417529135.81)                                 renamed as /o7th.ico
./sub-dir (NEWER_1417529135.81)/getyou.ico (NEWER_1417529079.87) renamed as /sub-dir (NEWER_1417529135.81)/getyou.ico
./sub-dir (NEWER_1417529135.81)/o7pm.ico (NEWER_1417529184.89)   renamed as /sub-dir (NEWER_1417529135.81)/o7pm.ico
./getyou.ico (NEWER_1417529079.87)                               renamed as /getyou.ico
./o7pm.ico (NEWER_1417529184.89)                                 renamed as /o7pm.ico
  • All [^/]*(.*) .*$ matches only the last part of the path that doesn't contain a /. And
  • In above regex, (.*) is a group of matching everything after last / and before a space. Its back-reference will be $1.
  • .*$ matches everything to end$ of files name after space.
  • Finally in replacement part of rename s/.../REPLACEMENT/, we just kept the matched group that is between last \ and a space(.*) which is known as group of matches.
0
2

You should consider using the quotes outside the regex (within, they are taken literally as quotes), and escape (. Try;

rename -n 's/ \(NEWER_\d{10}.\d{2}\)$//' *NEWER*

The precision of the expression might not be necessary, but you can't be too cautious when modifying files.

3
  • all this is doing is hanging with reading filenames from STDIN I am already inside the Parent folder where all these files are
    – Kevin
    Dec 15, 2014 at 20:59
  • @Kevin "If no filenames are given on the command line, filenames will be read via standard input." And since the shell leaves *NEWER* as it is if no expansions are found, you must have made a mistake, or are using a shell which replaced an unmatched wildcard with nothing.
    – muru
    Dec 15, 2014 at 21:05
  • copied and pasted, into Ubuntu 14.10 shell
    – Kevin
    Dec 15, 2014 at 21:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .