【问题标题】:How to use grep command in linux with []如何在带有 [] 的 linux 中使用 grep 命令
【发布时间】:2022-09-23 23:27:15
【问题描述】:

我想使用 grep 命令检查此字符串中是否存在空格后的 [200]

https://wwww.example.com/2000/file200.js [200]
https://wwww.example.com/2020/file201.js [404]

我试图 grep \"[200]\" 和 grep \"\\[200\\]\" 但他们都没有工作。

在用 grep 检查后我也需要保存链接,例如它会是这样的

cat links.txt | grep \"[200]\" > output.txt

output.txt 应该包含链接,而不是状态代码。

  • none of them worked 是什么意思?是否有错误消息或不正确的输出? grep \"\\[200\\]\" 在 GNU grep 上匹配。是不是匹配后要去掉状态码的问题?

标签: bash grep


【解决方案1】:

像这样的东西?

-F, --fixed-strings PATTERNS 是字符串

grep -F '[200]' file | cut -d' ' -f1

【讨论】:

    【解决方案2】:

    awk

    awk -F'[][]' '/\[200\]$/{print $1}' links.txt
    

    使用具有 -P 标志的 GNU grep

    grep -Po '.*(?=\[200\])' links.txt
    

    【讨论】:

      【解决方案3】:

      你的例子对我来说非常适合我的转义

       echo "https://wwww.example.com/99/file99.js [200]" | grep "\[200\]"
      

      然后,如果您只想要第一部分,您可以使用awk,它就像您可以在终端中使用的迷你编程语言。其中print $1 只打印第一个空格之前的字符

      echo "https://wwww.example.com/99/file99.js [200]" | grep "\[200\]" | awk '{print $1}'
      

      输出:

      https://wwww.example.com/99/file99.js
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-18
        • 1970-01-01
        • 2013-11-21
        • 1970-01-01
        • 2016-04-08
        相关资源
        最近更新 更多