gpt4 book ai didi

grep - 查找以 "+"结尾的行

转载 作者:行者123 更新时间:2023-12-01 06:49:13 26 4
gpt4 key购买 nike

我无法形成一个 grep 正则表达式,它只会找到那些以 + 号结尾的行。示例:

应该匹配 - This is a sample line +

不应该匹配 - This is another with + in betweenThis is another with + in between and ends with +

最佳答案

请使用$ 来指示行尾:

grep '+$' file

例子

$ cat a
This is a sample line +
This is another with + in between
hello

$ grep '+$' a
This is a sample line +

更新

What if I want to display lines which only has + in the end. Even if a line is like this This is a line with + in bw and in the end +. I don't want this line to be matched.

然后你就可以使用awk了:

awk '/\+$/ && split($0, a, "\+")==2' file

说明

  • /\+$/ 匹配以 + 结尾的行。
  • split($0, a, "\+")==2 根据 + 分隔符将字符串分成 block 。返回值是件数,所以2表示只包含一个+

例子

$ cat a
This is a sample line +
This is another with + in between
Hello + and +
hello

$ awk '/\+$/ && split($0, a, "\+")==2' a
This is a sample line +

关于grep - 查找以 "+"结尾的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22147274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com