【问题标题】:Grep returns sequence of aces instead of the result I expectGrep 返回 ace 序列而不是我期望的结果
【发布时间】:2015-01-08 09:44:11
【问题描述】:

我有一个名为 threads.log 的文件,这是该文件的示例

Threads:    40
Threads:    1
Threads:    1
Threads:    3
Threads:    5
Threads:    5
Threads:    1
Threads:    5
// rest

我在终端中这样做: echo $(cat threads.log | grep -o [0-9]*)

这是输出:1 1 1 1 1 1 1,而不是预期的数字。为什么会这样?

【问题讨论】:

  • 您的当前目录中是否有一个名为1 的文件?
  • 不确定,但您的代码对我有用。尝试删除 -o 以查看 1 背后的内容
  • @ExcelledProducts 运行touch 1,然后再次尝试该命令,看看会得到什么。
  • 我得到了你的输出。 1 1 1
  • @ExcelledProducts 完全正确。这就是 shell globbing 为你工作。比较 echo [0-9]*echo '[0-9]*',如果您需要,可以更清楚地了解那里发生的情况。

标签: linux bash shell ubuntu grep


【解决方案1】:

这条线有很多错误(或次优)。

echo $(cat threads.log | grep -o [0-9]*)

包装 echo 完全没用(它确实有作用但没什么用处),删除它。

cat threads.log | grep -o [0-9]*

不需要cat | grep grep 直接取文件。

grep -o [0-9]* threads.log

[0-9]* 是一个 shell glob。如果你有,而且我希望你有一个以当前目录中的数字开头的文件,那么 shell 会将 [0-9]* 扩展到匹配文件列表中,并且你的 grep 将不会得到你期望的参数。引用模式。

grep -o '[0-9]*' threads.log

它可以匹配零位并且不产生输出。你想要一个或多个数字,所以使用\+

grep -o '[0-9]\+' threads.log

【讨论】:

  • 我希望我能加两次。这是非常正确的。
  • 我不得不承认对最后一步有点惊讶。 * 的行为让我觉得有点奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多