如何在字符串和字符之间提取文本?

时间:2013-07-30 02:27:17

标签: bash shell unix sed

我的文本文件中有这些行:

msg_wdraw[] = "whatever a sentence here,"
               "This is the second part of this text1 ."
msg_sp2million[] = "whatever a sentence here,"
                  "This is the second part of this text2."

我需要msg_sp2million和句点“。”之间的句子。并打印出来。

即(“这里不管句子”,      “这是本文的第二部分。”)

我试过了:sed -n "/msg_sp2million/,/./p" filename.txt

但是,这个sed命令也会返回msg_wdraw的值(第一个变量)

我还尝试了awkgrep,其他sed .....但最终失败了。 我该如何解决这个问题?为什么这不仅会返回msg_sp2million的值以及msg_wdraw的值?

请帮助@〜@

3 个答案:

答案 0 :(得分:0)

也许是这样的:

awk '/msg_sp2million/{ split($0,a,"="); print a[length(a)]; getline; print}' file.txt

匹配正则表达式,打印=之后的内容,获取下一行,并打印出来。

返回:

 "whatever a sentence here,"
                  "This is the second part of this text2."

答案 1 :(得分:0)

我无法将评论GNU awk从某个版本开始(显然3.1.5,另见http://awk.freeshell.org/AwkFeatureComparison)。

提示:尝试

awk -W posix '/msg_sp2million/{ split($0,a,"="); print a[length(a)]; getline; print}' file.txt

非GNU 环境中,您将99%肯定会收到错误消息,例如: G。关于在标量上下文中使用数组。

以下解决方案也适用于HP-UX工作站:
(当然,-W posix可能会被省略,但在测试阶段总是非常宝贵的)

awk -W posix '/msg_sp2million/{ amount=split($0,a,"="); print a[amount]; getline; print}' file.txt

答案 2 :(得分:0)

使用简单的awk命令:

awk -F '= *' -v RS='.' -v ORS='."\n' '$1 ~ /msg_sp2million/ {sub(/" *\n */, "\" ", $2);
         print $2}' file
"whatever a sentence here," "This is the second part of this text2."