在普通bash中使用正则表达式提取子字符串

时间:2012-11-14 04:52:02

标签: regex bash

我正在尝试使用bash从字符串中提取时间,而且我很难搞清楚它。

我的字符串是这样的:

US/Central - 10:26 PM (CST)

我想提取10:26部分。

任何人都知道只使用bash这样做的方法 - 不使用sed,awk等?

就像,在PHP中我会使用 - 不是最好的方法,但它的工作原理如下:

preg_match( ""(\d{2}\:\d{2}) PM \(CST\)"", "US/Central - 10:26 PM (CST)", $matches );

感谢您的帮助,即使答案使用了sed或awk

5 个答案:

答案 0 :(得分:169)

使用纯

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

使用bash正则表达式的另一种解决方案:

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

使用grep和环顾高级正则表达式的另一种解决方案:

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

使用sed的另一种解决方案:

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

使用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}}}'

答案 1 :(得分:63)

    echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"

-n      suppress printing
s       substitute
^.*     anything at the beginning
-       up until the dash
\s*     any space characters (any whitespace character)
\(      start capture group
\S*     any non-space characters
\)      end capture group
.*$     anything at the end
\1      substitute 1st capture group for everything on line
p       print it

答案 2 :(得分:24)

快速'无脏,无正则表达,低稳健性斩波技术

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

答案 3 :(得分:-1)

如果您的字符串是

foo="US/Central - 10:26 PM (CST)"

然后

echo "${foo}" | cut -d ' ' -f3

会做。

答案 4 :(得分:-1)

foo="美国/中部 - 晚上 10:26 (CST)"

echo ${foo} |日期 +%H:%M

相关问题