bad*_*ger 1 bash scripting grep
Bash的新手,使用grep等,发现它令人困惑。说我有一个看起来像这样的文件:
ABC: first example [1.0] ----
ABC: second example [1.1] ----
DEF: third example [1.2] ----
DEF: fourth example [1.3] ----
Run Code Online (Sandbox Code Playgroud)
如何使用grep获取以ABC开头,以example单词结尾的所有行,并在example之后的行中切掉所有内容?
所需的输出
ABC: first example
ABC: second example
Run Code Online (Sandbox Code Playgroud)
鉴于:
$ echo "$txt"
ABC: first example [1.0] ----
ABC: second example [1.1] ----
DEF: third example [1.2] ----
DEF: fourth example [1.3] ----
Run Code Online (Sandbox Code Playgroud)
您可以使用sed:
$ echo "$txt" | sed -n 's/\(^ABC.*example\).*$/\1/p'
ABC: first example
ABC: second example
Run Code Online (Sandbox Code Playgroud)
如果您的内容在文件中,则可以执行以下操作:
$ sed -n 's/\(^ABC.*example\).*$/\1/p' file
Run Code Online (Sandbox Code Playgroud)
说明:
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
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用awk:
$ echo "$txt" | awk 'match($0, /^ABC.* example/){print substr($0, RSTART, RLENGTH)}'
ABC: first example
ABC: second example
Run Code Online (Sandbox Code Playgroud)
如果你想使用单词边界(以便例如比不同的例子或非实例和*例子只是匹配作为一个独立的字),你可以这样做:
$ echo "$txt" | sed -n -E 's/(^ABC.*[[:<:]]example[[:>:]]).*$/\1/p'
Run Code Online (Sandbox Code Playgroud)
或者,使用gawg:
$ echo "$txt" | gawk 'match($0, /^ABC.*\<example\>/){print substr($0, RSTART, RLENGTH)}'
Run Code Online (Sandbox Code Playgroud)