在Bash中的两个字符之间提取string

我需要帮助提取Bash中“@”符号和空格“”之间的string。

我正在使用Python的Twitter工具,输出是这样的:

430438229200740352 2014-02-03 14:30:45 CST <HorizonAwon> @SawBlastt @WereAutomatic 101 for me to join as well 

我需要提取两个string:

SawBlastt

WereAutomatic

我也需要将它们分别设置为一个单独的variables。 我试着用sedgrep搞乱,但没有成功的结果。 我真的坚持这一点。 帮助非常感谢。 谢谢!

您可以使用:

 s='430438229200740352 2014-02-03 14:30:45 CST <HorizonAwon> @SawBlastt @WereAutomatic 101 for me to join as well' grep -oP '@\K[^ ]*' <<< "$s" SawBlastt WereAutomatic 

另一个gnu grep命令,我主要使用。

 grep -Po "(?<=@)[^ ]*" file 

BASH有自己的正则表达式匹配功能。

 s="430438229200740352 2014-02-03 14:30:45 CST <HorizonAwon> @SawBlastt @WereAutomatic 101 for me to join as well" if [[ $s =~ @([A-Za-z]+)\ @([A-Za-z]+) ]]; then echo ${BASH_REMATCH[1]} ${BASH_REMATCH[2]} fi 

解释一下,这里是man bash所说的话:

索引为n的BASH_REMATCH的元素是匹配第n个加括号的子表达式的字符串部分。

这设置像OP请求的变量

 $ cat foo.txt 430438229200740352 2014-02-03 14:30:45 CST <HorizonAwon> @SawBlastt @WereAutomatic 101 for me to join as well $ set $(awk '{print $6,$7}' FS='[ @]+' foo.txt) $ echo $1 $2 SawBlastt WereAutomatic