简体   繁体   English

我可以执行“非全局”grep 并仅捕获为每行输入找到的第一个匹配项吗?

[英]Can I perform a 'non-global' grep and capture only the first match found for each line of input?

I understand that what I'm asking can be accomplished using awk or sed, I'm asking here how to do this using GREP.我知道我要问的是可以使用 awk 或 sed 来完成的,我在这里问的是如何使用 GREP 来做到这一点。

Given the following input:给定以下输入:

.bash_profile
.config/ranger/bookmarks
.oh-my-zsh/README.md

I want to use GREP to get:我想使用 GREP 来获得:

.bash_profile
.config/
.oh-my-zsh/

Currently I'm trying目前我正在尝试

grep -Po '([^/]*[/]?){1}'

Which results in output:这导致输出:

.bash_profile
.config/
ranger/
bookmarks
.oh-my-zsh/
README.md

Is there some simple way to use GREP to only get the first matched string on each line?是否有一些简单的方法可以使用 GREP 仅获取每行上的第一个匹配字符串?

你根本不需要grep

cut -d / -f 1

I think you can grep non / letters like:我认为你可以 grep non /字母,如:

grep -Eo '^[^/]+'

On another SO site there is another similar question with solution.在另一个 SO 站点上,还有另一个类似的问题和解决方案。

The -o option says to print every substring which matches your pattern, instead of printing each matching line. -o选项表示打印与您的模式匹配的每个子字符串,而不是打印每个匹配的行。 Your current pattern matches every string which doesn't contain slashes (optionally including a trailing slash);您当前的模式匹配每个不包含斜杠的字符串(可选地包括尾部斜杠); but it's easy to switch to one which only matches this pattern at the beginning of a line.但是很容易切换到只在一行的开头匹配这个模式的模式。

grep -o '^[^/]*' file

Notice the addition of the ^ beginning of line anchor, and the omission of the -P option (which you were not really using anyway) as well as the silly beginner error {1} .请注意添加了^行锚点开头,省略了-P选项(无论如何您都没有真正使用过)以及愚蠢的初学者错误{1}

(I should add that plain grep doesn't support parentheses or repetitions; grep -E would support these constructs just fine, of you could switch to toe POSIX BRE variation which requires a backslash to use round or curly parentheses as metacharacters. You can probably ignore these details and just use grep -E everywhere unless you really need the features of grep -P , though also be aware that -P is not portable.) (我应该补充一点,普通grep不支持括号或重复; grep -E可以很好地支持这些结构,您可以切换到脚趾 POSIX BRE 变体,这需要反斜杠才能使用圆括号或花括号作为元字符。您可能可以忽略这些细节并在任何地方使用grep -E除非您确实需要grep -P的功能,但也要注意-P不可移植。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM