![提取包含“[...]”的模式后的第一个单词](https://linux22.com/image/62249/%E6%8F%90%E5%8F%96%E5%8C%85%E5%90%AB%E2%80%9C%5B...%5D%E2%80%9D%E7%9A%84%E6%A8%A1%E5%BC%8F%E5%90%8E%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%8D%95%E8%AF%8D.png)
当我尝试提取grep
匹配我的模式后的第一个单词时,我遇到问题。
让我给你看一个例子:
cat test.txt
[profile dev]
xxx
xxx
[profile prod]
xxx
xxx
现在我想提取“profile”后面的单词并最终将其分配给一个变量
我尝试使用grep
andawk
但似乎我无法仅提取这个词
grep -oP '(?<=profile\s/)\w+' /test.txt
也不会返回任何内容awk
:
awk '/^profile / {print $1}' /text.txt
也许是因为括号或者我不知道,你能帮我提个建议吗?
答案1
你的 awk 模式失败了,因为单词“profile”没有开始记录,[profile
而是......
awk '/^\[profile/ {gsub(/]/,""); print $2}' test.txt
dev
prod
另一种方法是加载数组,使用split
:
awk -F'[][]' '/profile/ {p=split($2,profiles," "); print profiles[2]}' test.txt
dev
prod