1

I have an html-type of file that somewhere includes a tag as follows:

<Currentnumber>0.3.5</Currentnumber>

How do I catch in a variable the value 0.3.5 and only this?

I have come as far as grepping the line as follows:

grep -E "<Currentnumber>.*</Currentnumber>$" myfile

I would appreciate if for educational purposes any answer also provided an explanation of the grep parameters used.

Pls note that the line starts with some empty spaces (or tabs), this is why the following will not work

grep -E "^<Currentnumber>.*</Currentnumber>$" myfile
  • 3
    Obligatory link to Using regular expressions with HTML tags – Jeff Schaller Feb 13 '18 at 17:39
  • 2
    HTML and XML are not regular languages and one should not be attempting to parse them with regular expressions. – DopeGhoti Feb 13 '18 at 17:40
  • @DopeGhoti so what is the best/recommended way of going about this? – pkaramol Feb 13 '18 at 17:41
  • 2
    HTML or XML parsers exist. Use the right tool for the right job. Such as xmllint --xpath. – DopeGhoti Feb 13 '18 at 17:43
4

Never parse html with regex ! That's the most common mistake on stackexchange sites.

Better use a XML/HTML parser like , or saxon-lint my own project

Examples :

xmllint --xpath '//Currentnumber/text()' file.html
xmlstarlet sel -t -v '//Currentnumber/text()' file.html
saxon-lint --xpath --html '//Currentnumber/text()' file.html

Check: Using regular expressions with HTML tags

  • I am on an immutable container with no option of installing something and these tools are not available. – pkaramol Feb 14 '18 at 8:14
  • Tell your sysOp or devOps to add them in the container – Gilles Quenot Feb 14 '18 at 13:48
-2

Use sed and regex

sed -e 's/<Currentnumber>\(.*\)<\/Currentnumber>/\1/' file.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.