Bash 如何在第二次出现时提取两个单词之间的文本-unix shell脚本

Bash 如何在第二次出现时提取两个单词之间的文本-unix shell脚本,bash,unix,awk,sed,grep,Bash,Unix,Awk,Sed,Grep,我试图提取一个字符串,该字符串包含字符串中两个单词之间的所有内容: 输入: Please find the text [ This is a sample text [ Hello World - Earth ] ] 输出: Hello World - Earth 第二次出现[和]之间出现的文本如果您的grep支持-p选项PCRE,请尝试: grep -Po "\[.*?\[\K.+?(?=])" <<< "Please find the te

我试图提取一个字符串,该字符串包含字符串中两个单词之间的所有内容:

输入:

Please find the text [ This is a sample text [ Hello World - Earth ] ]
输出:

Hello World - Earth
第二次出现[和]

之间出现的文本如果您的grep支持-p选项PCRE,请尝试:

grep -Po "\[.*?\[\K.+?(?=])" <<< "Please find the text [ This is a sample text [ Hello World - Earth ] ]"
\K序列告诉引擎从中放弃前面的匹配 作为查找的匹配结果。 模式?=]是与右方括号匹配的前视图 也将比赛从结果中排除。 使用awk,您可以执行以下操作

$ awk -F'[][]' '{print $3}' <<< "Please find the text [ This is a sample text [ Hello World - Earth ] ]"
 Hello World - Earth 

这可能适用于GNU sed:

sed -E 's/^[^[]*\[(.*)\].*/\1/;s//\1/' file
查找第一组[…]之间的所有内容,然后重复此过程以查找第二组[…]之间的所有内容

可编程版本:

 sed -E ':a;/^[^[]*\[(.*)\].*/!d;s//\1/;x;s/^/x/;/x{2}/{x;b};x;ta' file
更改x{2}中所需深度的整数


注意:这是一行一行的工作方式,不适用于带引号的方括号。

这是一个grep、sed等贪婪匹配不成问题的地方,即echo请查找文本[这是一个示例文本[Hello World-Earth]]| sed's/^.[[]/;s/[].$/':输出“Hello World-Earth”。祝你好运