Bash的新手,使用grep等并发现它令人困惑。假设我有一个看起来像这样的文件:
ABC: first example [1.0] ----
ABC: second example [1.1] ----
DEF: third example [1.2] ----
DEF: fourth example [1.3] ----
我怎样才能使用grep来获取所有以ABC开头的行,以单词example结束,并在示例后删除行中的所有内容?
期望的输出
ABC: first example
ABC: second example
答案 0 :(得分:3)
使用GNU grep
:
grep -o '^ABC.*\<example\>'
-o
仅获得匹配的部分
^ABC
在该行的开头匹配ABC
.*
贪婪地匹配example
之前的所有内容,\<
匹配example
之前的零宽度字边界,同样\>
匹配{}之后的字边界{1}}
请注意,这会匹配以example
开头且ABC
开头的行,而不一定是example
的最后一个字。在后一种情况下,如果您只想将字母(字符类example
)作为单词构成字符进行匹配,则在[:alpha:]
支持此情况时利用PCRE(-P
)(例如GNU {{ 1}})并使用零宽度正向前瞻:
grep
示例:强>
grep
答案 1 :(得分:3)
假设:
$ echo "$txt"
ABC: first example [1.0] ----
ABC: second example [1.1] ----
DEF: third example [1.2] ----
DEF: fourth example [1.3] ----
您可以使用sed
:
$ echo "$txt" | sed -n 's/\(^ABC.*example\).*$/\1/p'
ABC: first example
ABC: second example
如果您的内容位于文件中,则可以执行以下操作:
$ sed -n 's/\(^ABC.*example\).*$/\1/p' file
说明:
sed -n 's/\(^ABC.*example\).*$/\1/p'
^ don't print unless p directive
^ substitute
^ ^ capture group -- parens need to be escaped
^ ABC at start of line
^ anything up to example
^ everything after example to end of line
^ replace entire line with capture group
^ p means print that if sub made
或者,您可以使用awk
:
$ echo "$txt" | awk 'match($0, /^ABC.* example/){print substr($0, RSTART, RLENGTH)}'
ABC: first example
ABC: second example
如果您想使用word boundaries(以便示例与示例或 nonexample 不同,*示例仅匹配作为一个单独的词你可以做:
$ echo "$txt" | sed -n -E 's/(^ABC.*[[:<:]]example[[:>:]]).*$/\1/p'
或者gawg
:
$ echo "$txt" | gawk 'match($0, /^ABC.*\<example\>/){print substr($0, RSTART, RLENGTH)}'