英文:
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
-odisplay only matching part-Eis to useEREregex 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 '\bs[[:alpha:]]*n\b' file
<p>
sn
soon
saaaaan
siiiiiiiiin
sXXXXXXn
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论