【问题标题】:grep variable string in filegrep 文件中的变量字符串
【发布时间】:2016-05-03 10:18:56
【问题描述】:

我必须在文件中找到这个字符串:

200 https://www.example.example

值 200 是随机的,我必须找到每个 HTTP 返回码(例如 200、301、404 等...等)

我怎样才能只用返回码变量 grep 这个字符串(我不想在 grep 命令中指定每个返回码)?

cat file.txt | grep "*** http*" 

但它不起作用。

【问题讨论】:

  • 不太清楚你在这里问什么。尝试阅读How to Ask 并提供minimal reproducible example 以便我们更好地理解。提供相关的输入和所需的输出很重要。
  • 只取每行的前 3 个字符怎么样?
  • grep "*** http*" 与您想要的正则表达式不接近。如果您要尝试使用任何使用正则表达式的工具(grep、sed、awk、perl、ruby 等......),您应该找到某种正则表达式教程。

标签: regex linux bash grep match


【解决方案1】:

所以你想匹配任何以三位数开头,后跟“http”的行?

grep -E '^[0-9]{3} http' file.txt

fedorqui 建议的更准确(谢谢)是这样的:

grep -E '^[1-5][0-9]{2} http' file.txt

这匹配 100-599 范围内的数字,更接近 HTTP 状态代码的范围。

【讨论】:

【解决方案2】:

首先,不需要catgrep。它本身可以接受一个文件参数。

你可以这样做:

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt

这将为您提供与您的条件匹配的每一行。

如果您只需要返回码,您可以运行另一个 grep 或使用其他命令,例如使用 cut

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt | cut -d ' ' -f1

和 grep,

grep '^[1-5][0-9]\{2\}[[:blank:]]\+http' file.txt | grep -o '^[0-9]\+'

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2011-01-07
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2021-07-19
    • 2016-05-07
    • 2020-05-11
    • 2023-03-27
    相关资源
    最近更新 更多