使用grep查找以指定字母开头和结尾的单词在文件中的用法是?

huangapple go评论39阅读模式
英文:

how would i use grep to find words in a file that start and end with specified letter?

问题

I want to match all the words in a file that start with "s" and end with "n" so i tried this before

grep "\bs.*n\b"

but it contain part of the line and i need just words

英文:

I want to match all the words in a file that start with "s" and end with "n" so i tried this before

grep "\bs.*n\b"  

but it contain part of the line and i need just words

答案1

得分: 2

Here is the translated content:

像这样,假设单词可以由2个字符到∞个字符组成:

grep -oE ''\bs[[:alpha:]]*n\b'' file
  • -o 显示匹配的部分
  • -E 用于使用ERE正则表达式风格

正则表达式的匹配如下:

节点 说明
\b 单词字符(\w)与非单词字符之间的边界锚点
s s
[[:alpha:]]* 任何字符:字母(零次或多次)
n n
\b 单词字符(\w)与非单词字符之间的边界锚点

示例:

$ cat file
sn
aaaaa soon sss saaaaan
bbb siiiiiiiiin xxx sXXXXXXn
$ grep -oE ''\bs[[:alpha:]]*n\b'' file

希望这能帮助您理解代码和正则表达式的含义。

英文:

Like this, assuming words can be from 2 characters to ∞:

grep -oE '\bs[[:alpha:]]*n\b' file
  • -o display only matching part
  • -E is to use ERE regex flavor

The regular expression matches as follows:

Node Explanation
\b the boundary anchor between a word char (\w) and something that is not a word char anchor
s s
[[:alpha:]]* any character of: letters (zero or more times)
n n
\b the boundary anchor between a word char (\w) and something that is not a word char anchor

Example:

$ cat file
sn
aaaaa soon sss saaaaan
bbb siiiiiiiiin xxx sXXXXXXn

<p>

$ grep -oE &#39;\bs[[:alpha:]]*n\b&#39; file

<p>

sn
soon
saaaaan
siiiiiiiiin
sXXXXXXn

huangapple
  • 本文由 发表于 2023年5月8日 02:24:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195608-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定