简体   繁体   English

在 grep 中,如何拉取不以空格字符开头的字符串?

[英]In grep, how to pull a string that does not start with a whitespace character?

I am trying to pull out percentage completion in curl output.我试图在 curl output 中提取完成百分比。 The string is given as:字符串给出为:

96 2001G 0 0 96 1920G 0 82.2M 6:17:53 6:01:25 0:12:35 97M

My grep -oP (?<=\s)[1-9][0-9]{0,2}(?=\s) command pulls out the middle 96 instead of the 96 to the left.我的grep -oP (?<=\s)[1-9][0-9]{0,2}(?=\s)命令拉出中间的 96 而不是左侧的 96。 How can I target the first 96 instead?如何改为定位前 96 个? I tried (?<=\s*)[1-9][0-9]{0,2}(?=\s) and (?<=^\s)[1-9][0-9]{0,2}(?=\s) to no avail.我试过(?<=\s*)[1-9][0-9]{0,2}(?=\s)(?<=^\s)[1-9][0-9]{0,2}(?=\s)无济于事。 Thanks.谢谢。

The wording of your question ("pull a string that does not start with whitespace") and the regular expressions you have tried (lookbehind assertions that are looking for white space before the string) do not match up , so it is not entirely clear what you are after.你的问题的措辞(“拉一个不以空格开头的字符串”)和你尝试过的正则表达式(在字符串之前寻找空格的后向断言)不匹配,所以不完全清楚是什么你在追求。

If you are looking for all percentages including those separated by white space and those that are at the very beginning of the line (no white space before but white space after) and those at the very end of the line (white space before but no white space after), then:如果您正在查找所有百分比,包括由空格分隔的百分比和位于行首的百分比(之前没有空格但之后有空格)和行尾的百分比(之前有空格但没有白色之后的空格),然后:

Try:尝试:

grep -oP '(?<!\S)[1-9][0-9]{0,2}(?!\S)'

You need to use negative lookbehind and lookahead assertions : (?<!\S) and (?!\S)您需要使用否定的lookbehind 和lookahead 断言(?<!\S)(?!\S)

The negative lookbehind assertion states that the percentage must not be preceded by a non-white space character.否定的lookbehind断言表明百分比前面不能有非空白字符。 This is a double-negative that either white space or the start of the line or string satisfies.这是一个双重否定,空格或行或字符串的开头都满足。 Likewise the negative lookahead assertion states that the percentage must not be followed by a non-white space character, again a double negative that either white space or the end of the line or string satisfies.同样,否定的前瞻断言指出百分比后面不能跟非空白字符,同样是空格或行尾或字符串满足的双重否定。

See Regex Demo见正则表达式演示

But if you are only interested in the percentage at the beginning of the line then:但是,如果您只对行首的百分比感兴趣,那么:

Try:尝试:

grep -oP '^[1-9][0-9]{0,2}(?!\S)'

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

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