In my build.xml file I want to extract time using regex in shell scripting which will be in d hr d min d sec format. And time will not always be in same pattern it will differ for eg:

1 sec

1 min

2 min 3 sec

4 hr 5 min

Now I want to use regular expression to get the time value from my file. In the xml file it will be in value tag:

<value>1 hr 54 min</value>

I used cat build.xml | grep -oP '(?<=<value>).*sec?(?=</value>)' but in this case it will print only for sec or likewise I can print only for min.

Please help me in this regex.

有帮助吗?

解决方案

how about this?

echo '<value>4 hr 3 sec</value>' 
| grep -oP '(?<=<value>)(\d+\s+hr)?(\s*\d+\s+min)?(\s*\d+\s+sec)?(?=</value>)'

4 hr 3 sec

echo '<value>3 sec</value>' |
 grep -oP '(?<=<value>)(\d+\s+hr)?(\s*\d+\s+min)?(\s*\d+\s+sec)?(?=</value>)'

3 sec

其他提示

Use this regex:

(?<=<value>)(\\d+ (hr|min|sec) ?){1,3}(?=</value>)

It's not exactly prescriptive (for example it allows "3 hr 4 hr"), but it should be good enough to work for you.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top