发现模式后Grep为2个单词

时间:2012-12-07 12:06:44

标签: linux grep

该场景是我有一个文件并包含一个字符串“日期和时间是2012-12-07 17:11:50”

我搜索过并找到了一个命令

grep 'the date and time is' 2012-12-07.txt | cut -d\   -f5

它只显示第5个单词,我需要第5个和第6个的组合,所以我试过

grep 'the date and time is' 2012-12-07.txt | cut -d\   -f5 -f6 

但它的错误。

现在,如何用一个命令grep第5和第6个单词

我只需要输出2012-12-07 17:11:50

3 个答案:

答案 0 :(得分:3)

你应该可以使用

$ grep 'the date and time is' 2012-12-07.txt | cut -d' ' -f6-7

检查the man page以获取-f选项参数的语法。

答案 1 :(得分:0)

我猜它不是第5和第6而是第6和第7

grep 'the date and time is' 2012-12-07.txt |awk '{print $6,$7}'

答案 2 :(得分:0)

这听起来像awk的工作,可能比构建由多个流程组成的管道快一点:

pax> echo 'hello
           the date and time is 2012-12-07 17:11:50
           goodbye' | awk '/the date and time is/ {print $6" "$7}'
2012-12-07 17:11:50

它将搜索和修改结合在一个命令中。

请注意,此解决方案与您的解决方案一样,如果在您的搜索字符串之前上有内容,则无法提供帮助,但awk也可以这样做,取决于您的需求的复杂性,例如:

pax> echo 'hello
           Today (Friday), the date and time is 2012-12-07 17:11:50
           goodbye' | awk '/the date and time is/ {
                               sub (".*is","",$0);
                               print $1" "$2
                               }'
2012-12-07 17:11:50