Slashlinux
Slashlinux

Reputation: 57

match two digits with colon

I want to match 2 digits like (30:02:40) resulted from file index.txt, but i am stuck on if condition, i don't know how to compare the result and do something.

index.txt

<tr><td>device</td> <td>10.10.10.1</td> <td>64232</td> <td>1</td> <td bgcolor=Red>30:02:40</td><tr>

script.sh

#!/bin/bash
output=$(cat index.txt |  sed -e 's/>/ /g;s/</ /g'| awk '{print $16}')
if [ $output == '[0-9][0-9]:[0-9][0-9]:[0-9][0-9]' ]; then
        echo "successful"
else
        echo "$output"
fi

tx

Upvotes: 0

Views: 141

Answers (4)

MostWanted
MostWanted

Reputation: 571

Yes some html parser would be better, but a pure bash solution might be:

grep -oP "\d+:\d+:\d+" index.txt

Upvotes: -1

karakfa
karakfa

Reputation: 67507

why not do the matcing in awk, instead of just {print $16}

... | awk '$16~/^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/{print "successful"; exit} {print $16}' 

you can also incorporate the first sed into this by just setting the right delimiters, but need to know the structure better to pinpoint the required field.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

xmlstarlet/xmllint are the right tools for manipulating XML/HTML data.
(For xmlstarlet : the only requirement is that your content should be a valid HTML/XML document/fragment):

xmlstarlet sel -t -v "//tr/td[@bgcolor='Red']" -n \
<(sed -E 's/([^[:space:]=<>]+=)([^[:space:]=<>]+)/\1"\2"/g; s/<tr>$/<\/tr>/' index.txt)

The output:

30:02:40

xmllint approach:

xmllint --html --xpath "//tr/td[@bgcolor='Red']/text()" index.txt
30:02:40

Upvotes: 1

user1333144
user1333144

Reputation: 49

You have two issues:

  • Single square bracket tests are not able to handle those kinds of wildcards, but you can use the extended test command with double brackets.
  • Single-quote marks means that your wildcards are ignored and the string is treated as being verbatim.

With these two tweaks it works:

if [[ $output == [0-9][0-9]:[0-9][0-9]:[0-9][0-9] ]]; then
    echo "successful"
else
    echo "$output"
fi

Upvotes: 1

Related Questions