Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a folder with a bunch of html files numbered sequentially (file1.html, file2.html, etc).

I would like to rename each file according to the tag in each file.

So if file1.html contains <title>Page Name</title>, I would like the script to rename the file Page Name.html.

How do I do this on linux?

share|improve this question
Sanity check: Are all titles unique? (Check this with grep title *.html ). If not you are ending up with duplicate file names (or rather, with errors or lost files when two files try to get renamed to the same file name) – Hennes Feb 3 '13 at 18:09
up vote 2 down vote accepted

This would be a very simplistic approach assuming your document is somewhat well formed:

#!/usr/bin/env bash
for f in *.html;
   title=$( grep -oP '(?<=<title>).*(?=<\/title>)' "$f" )
   mv -i "$f" "${title//[^a-zA-Z0-9\._\- ]}".html   

Some explanation of what happens:

  • To get only the actual title, we'll use grep and Perl regular expressions. There are look-aheads and look-behinds to filter out the actual HTML tags and only get the title. It's a complicated-looking regex, but you can't easily output only the captures with grep.
  • Make sure to always quote your variables ("$f") so the whole thing works if files have whitespace in their name.
  • By default mv will overwrite existing files. Use mv -i to avoid that and have your shell prompt you before overwriting.
  • Any character except letters, numbers, ., _ and -, as well as a space, will be removed from the file name. We do this with substring replacement.
  • To remove all whitespace, use mv -i "$f" "${title//[^a-zA-Z0-9\._\-]}".html
  • To keep the actual page title as-is, simply use mv "$f" "$title".html.
share|improve this answer
Use mv -i or some other method to prevent losing files with duped titles. Also consider adding something with tr or sed to replace non-alphanumerical characters with _ or something. – frostschutz Feb 3 '13 at 18:31
mv will not overwrite an existing file unless you use -f. – ott-- Feb 3 '13 at 18:32
@ott yes it will. At least on any Linux system I have ever used. You may have mv set up as an alias to mv -i on your system. – terdon Feb 3 '13 at 18:36
Arg. There was an alias mv='mv -n', which acts silently (and does not overwrite an existing file). – ott-- Feb 3 '13 at 18:48
@frostschutz Thanks for the suggestion. Did some sanitizing there. – slhck Feb 3 '13 at 18:49

You must log in to answer this question.

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