在纯bash中使用regexp提取子字符串 [英] Extract substring using regexp in plain bash
问题描述
我正在尝试使用bash从字符串中提取时间,而我很难确定它的时间.
I'm trying to extract the time from a string using bash, and I'm having a hard time figuring it out.
我的字符串是这样的:
US/Central - 10:26 PM (CST)
我想提取10:26
部分.
有人知道只有使用bash才能做到这一点-不使用sed,awk等吗?
Anybody knows of a way of doing this only with bash - without using sed, awk, etc?
就像,在PHP中,我将使用-不是最好的方法,但它的工作原理是:
Like, in PHP I would use - not the best way, but it works - something like:
preg_match( ""(\d{2}\:\d{2}) PM \(CST\)"", "US/Central - 10:26 PM (CST)", $matches );
感谢您的帮助,即使答案使用sed或awk
Thanks for any help, even if the answer uses sed or awk
推荐答案
使用纯 bash :
$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt
使用bash正则表达式的另一种解决方案:
another solution with bash regex :
$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
echo ${BASH_REMATCH[1]}
使用grep
和环视高级正则表达式的另一种解决方案:
another solution using grep
and look-around advanced regex :
$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"
使用sed的另一种解决方案:
another solution using sed :
$ echo "US/Central - 10:26 PM (CST)" |
sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'
使用perl的另一种解决方案:
another solution using perl :
$ echo "US/Central - 10:26 PM (CST)" |
perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'
最后一个使用awk:
$ echo "US/Central - 10:26 PM (CST)" |
awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'
这篇关于在纯bash中使用regexp提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!