如何在unix中提取两个单词之间的文本? [英] How to extract text between two words in unix?
问题描述
我
我
使用
基本
sed
表达 :-
I
am
using
basic
sed
expression :-
sed -n "am/,/sed/p"
获取am"和sed"之间的文本这将输出am \n using \n basic \n sed".但我真正的问题是字符串是否为 :-
to get the text between "am" and "sed" which will output "am \n using \n basic \n sed". But my real problem is if the string would be :-
我
我
使用
基本
格雷普
表达.
I
am
using
basic
grep
expression.
我在这句话中应用了上面的sed然后它给出了am \n using \n basic \n grep \n expression"它不应该给它.如何丢弃如果没有匹配则输出?
I applied the above sed in this sentence then it gave "am \n using \n basic \n grep \n expression" which it should not give it. How to discard the output if there would be no matching?
有什么建议吗?
推荐答案
问题中的命令(sed -n "/am/,/sed/p"
,注意添加的斜线)表示:
The command in the question (sed -n "/am/,/sed/p"
, note the added slash) means:
- 找到包含字符串
am
的行 - 并打印 (
p
) 直到出现包含sed
的行
- Find a line containing the string
am
- and print (
p
) until a line containingsed
occurs
因此它打印:
I am using basic grep expression
因为它包含am
.如果您要添加更多行,它们也会被打印出来,直到出现包含 sed
的行.
because it contains am
. If you would add some more lines they will be printed, too, until a line containing sed
occurs.
例如:
echo -e 'I am using basic grep expression.\nOne more line\nOne with sed\nOne without' | sed -n "/am/,/sed/p"
结果:
I am using basic grep expression.
One more line
One with sed
我认为 - 你想要做的就是这样:
I think - what you want to do is something like that:
sed -n "s/.*\(am.*sed\).*/\1/p"
示例:
echo 'I am using basic grep expression.' | sed -n "s/.*\(am.*sed\).*/\1/p"
echo 'I am using basic sed expression.' | sed -n "s/.*\(am.*sed\).*/\1/p"
sed -n "s/.*\(am.*sed\).*/\1/p"
这篇关于如何在unix中提取两个单词之间的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!