1

I want to know if there is a way to list all the html tags in a file. Lets say I have a file file.html

<html>
<head>
<title>Test</title>
</head>
<body>
This is a test
</body>
</html>

And I want to get a list of all the tags. That is:

<html>
<head>
<title>
</title>
</head>
<body>
</body>
</html>

I tried using sed,

cat file.html | sed 's/<[^>]*>//g'

But it removed all the html tags insted . . . .

3
  • 3
    WHY GOD, WHY?
    – Braiam
    Jul 23 '14 at 20:19
  • I have read that before. . . But there has to be a way v.v
    – gkmohit
    Jul 23 '14 at 20:22
  • Which shell? bash?
    – Cyrus
    Jul 23 '14 at 21:02
3

A quick hack with perl:

perl -wlne 'print for(/<.*?>/g)' file.html

But for a serious solution you should use a tool that really understands html/xml.

7
  • I need a bash solution only :( sorry about that:/
    – gkmohit
    Jul 23 '14 at 20:24
  • 1
    Be aware that your sed solution is not bash only...
    – michas
    Jul 23 '14 at 20:25
  • umm didnt know that :/ But your solution is so perfect :/
    – gkmohit
    Jul 23 '14 at 20:26
  • 1
    grep -oP '<.*?>' filename
    – Cyrus
    Jul 23 '14 at 20:33
  • @Cyrus also not bash-only...
    – derobert
    Jul 23 '14 at 20:35
2

Using an actual html parser isn't that hard:

perl -MHTML::Parser -E '
  $handler = sub {say "<".shift.">"};
  HTML::Parser->new(start_h => [$handler,"tag"], end_h => [$handler,"tag"])
              ->parse_file(shift @ARGV)
' file.html
<html>
<head>
<title>
</title>
</head>
<body>
</body>
</html>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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