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

时间:2014-02-05 20:36:50

标签: regex linux bash sed grep

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

我正在使用Python Twitter Tools,输出如下:

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

我需要提取两个字符串:

  

SawBlastt

     

WereAutomatic

我还需要将它们设置为单独的变量。我已经尝试过使用sed和grep,但没有成功的结果。我真的坚持这个。非常感谢帮助。谢谢!

4 个答案:

答案 0 :(得分:4)

您可以使用:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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个带括号的子表达式匹配的字符串部分。

答案 3 :(得分:0)

这设置了像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
相关问题