Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
2  
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
add comment

1 Answer 1

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;
do
   title=$( grep -oP '(?<=<title>).*(?=<\/title>)' "$f" )
   mv -i "$f" "${title//[^a-zA-Z0-9\._\- ]}".html   
done

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
1  
@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
show 2 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.