我正在尝试使用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
发布于 2012-11-14 12:54:29
使用纯bash:
$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt
使用bash regex的另一种解决方案:
$ [[ "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}}}'
发布于 2016-04-23 00:14:58
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
发布于 2012-11-14 16:01:58
快速脏、无正则表达式、低健壮性的斩波技术
string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"
https://stackoverflow.com/questions/13373249
复制相似问题