相当于 grep 到 awk 或 sed

Har*_*tel 6 grep sed awk

我想知道相当于

grep -oE '[^ ]+$' pathname
Run Code Online (Sandbox Code Playgroud)

awk 或 sed。如果有人能回答并解释,那就太好了。谢谢你。

cuo*_*glm 6

awk是 的超集grep,因此您也可以使用该grep模式awk

awk '{match($0, "[^ ]+$"); if (RSTART > 0) print substr($0, RSTART, RLENGTH)}'
Run Code Online (Sandbox Code Playgroud)

  • `awk` 是 `grep` 的超集吗?它们是两个独立的实用程序,具有两个不同的目的。你能解释一下你的意思吗? (2认同)
  • @Serg:`awk` 可以做任何 `grep` 能做的事情,在标准版本中 (2认同)

Ser*_*nyy 4

让我们首先回顾一下您的grep命令的作用:

  • 告诉只输出匹配的部分-ogrep不是整行
  • -E标志允许使用扩展正则表达式
  • '[^ ]+$'将匹配在行末尾重复一次或多次的任何非空格字符 - 基本上是行末尾的一个单词。

测试运行:

$ cat input.txt
to be or not to be
that is the question
$ grep -oE '[^ ]+$' input.txt                                      
be
question
Run Code Online (Sandbox Code Playgroud)

现在,我们怎样才能在 中做同样的事情awk呢?awk考虑到默认情况下对每行以空格分隔的条目(我们称之为单词 -awk称之为字段)进行操作,这很容易。因此,我们可以$NF使用 awk 进行打印 - 获取NF字段数量的变量并将其视为引用特定字段。但请注意,该grep命令只会匹配非空行,即那里至少有一个单词。因此,我们需要一个条件awk- 仅对字段NF数大于零的行进行操作。

awk 'NF{print $NF}' input.txt
Run Code Online (Sandbox Code Playgroud)

应该指出的是,GNU awk 至少支持扩展的正则表达式(我对其他人不太熟悉,所以不会对其他人提出要求)。因此,我们还可以根据 cuonglm 的答案写出一个变体:

$ awk '{if(match($0,/[^ ]+$/)) print $NF}' input.txt               
be
question
Run Code Online (Sandbox Code Playgroud)

使用 GNUsed也可以使用扩展的正则表达式 - 这需要-r标志,但不能简单地使用相同的正则表达式。需要使用反向引用\1

$ cat input.txt                                                                                                          
to be or not to be
that is the question
blah 

$ sed -r -e 's/^.* ([^ ]+)$/\1/' input.txt                                                                             
be
question
blah
Run Code Online (Sandbox Code Playgroud)

使用基本正则表达式可以获得所需的结果,如下所示:

$ cat input.txt                                                    
to be or not to be
that is the question
blah 
$ sed 's/^.* \([^ ].*\)$/\1/' input.txt                           
be
question
blah 
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请参阅这些帖子: